在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();
}
}
}
结果如下: