1. 程式人生 > >C# List 找出類中某個重複屬性變數

C# List 找出類中某個重複屬性變數

在List<T>中,找出類A中具有相同Phone屬性的物件,並輸出這些物件的ID值;

程式碼如下:

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

namespace Demo
{
    class A
    {
        public int ID;
        public int Phone;
    }

    class Program
    {
        void PrintResult()
        {
            List<A> aList = new List<A>()
            {
                new A(){ ID = 1, Phone= 123 },
                new A(){ ID = 2, Phone= 222 },
                new A(){ ID = 3, Phone= 333 },
                new A(){ ID = 4, Phone= 123 },
            };

            var result = from r in aList
                         group r by r.Phone into g
                         where g.Count() > 1
                         select g;
            //遍歷分組結果集
            foreach (var item in result)
            {
                foreach (A u in item)
                {
                    Console.WriteLine("ID: " + u.ID);
                }
            }
        }  

        public static void Main()
        {
            Program program = new Program();
            program.PrintResult();
            Console.ReadKey();
        }
    }
}

結果如下: