1. 程式人生 > >c# List<物件>獲取重複項,轉成Dictionary<key,List<物件>>

c# List<物件>獲取重複項,轉成Dictionary<key,List<物件>>

 

public class Car
    {
        public long ID { get; set; }
        public string Name { get; set; }
        public string OtherName { get; set; }
    }

 

static void Main(string[] args)
        {
            List<Car> cars = new List<Car>();
            cars.Add(new
Car() { ID = 1, Name = "紅旗", OtherName = "hq1" }); cars.Add(new Car() { ID = 2, Name = "賓士", OtherName = "bc1" }); cars.Add(new Car() { ID = 3, Name = "寶馬", OtherName = "bm1" }); cars.Add(new Car() { ID = 4, Name = "賓士", OtherName = "bc2" }); cars.Add(
new Car() { ID = 5, Name = "寶馬", OtherName = "bm2" }); //同名 var carSame = cars.GroupBy(x => x.Name).Where(x => x.Count() > 1).ToList(); foreach (var item in carSame) { Console.WriteLine(item.Key); } Console.WriteLine(
"---*---"); var carSameArr = cars.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(i => i.Key).ToArray(); foreach (string car in carSameArr) { Console.WriteLine(car); } Console.WriteLine("---*---"); var carDict = cars.GroupBy(x => x.Name).ToDictionary(x => x.Key, x => x.ToList()); //以下是輸出: foreach (KeyValuePair<string, List<Car>> pair in carDict) { Console.WriteLine(pair.Key); pair.Value.ForEach(x => Console.WriteLine(@"ID={0}, Name='{1}',OtherName='{2}'", x.ID, x.Name, x.OtherName)); Console.WriteLine(); } Console.ReadKey(); }

 

 

參考: