[C#] 無聊寫的linq 範例


//Rextester.Program.Main is the entry point for your code. Don't change it.
//Microsoft (R) Visual C# Compiler version 2.9.0.63208 (958f2354)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public enum DirTypeEnum
    {
        TopDir = 0,
        SubDir = 1
    }
    
    public class TestData
    {
        public int Id {get; set;}
        public int IsUsing {get; set;} 
        public string Name {get; set;}
        public DirTypeEnum Type {get; set;}
        public int? Parent {get; set;}
    }
    
    public class Program
    {
        public static void Main(string[] args)
        {
            var data = new List<TestData>();
            data.Add(new TestData {Id = 0, IsUsing = 1, Name = "Top Dir1", Type = DirTypeEnum.TopDir, Parent = null});
            data.Add(new TestData {Id = 1, IsUsing = 0, Name = "Sub Dir 1", Type = DirTypeEnum.SubDir, Parent = 0});
            data.Add(new TestData {Id = 2, IsUsing = 1, Name = "Sub Dir 2", Type = DirTypeEnum.SubDir, Parent = 0});
            data.Add(new TestData {Id = 3, IsUsing = 1, Name = "Top Dir2", Type = DirTypeEnum.TopDir, Parent = null});
            data.Add(new TestData {Id = 4, IsUsing = 0, Name = "Sub Dir 1", Type = DirTypeEnum.SubDir, Parent = 3});
            
            var topDir = data.Where(o=>o.Type == DirTypeEnum.TopDir).ToList();

            topDir.Select(x => {
                x.IsUsing = (data.Where(p => p.Parent== x.Id).Sum(l => l.IsUsing) >= 1?1:0);
                return x;
            }).ToList();
           
            foreach(var x in data)
            {
                Console.WriteLine($"Id = {x.Id}, IsUsing = {x.IsUsing}, Name = {x.Name}, Type = {x.Type}, Parent = {x.Parent}");
            }
        }
    }
}








留言

siuon寫道…
怎麼想到寫這個 XD
hamisme寫道…
幫我同事寫的範例 XD

熱門文章