在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();
}
}
}
结果如下:
本文通过一个具体的C#代码示例介绍了如何使用LINQ来找出具有相同电话号码的对象,并输出这些对象的ID值。该示例展示了如何创建一个类`A`,包含两个属性:`ID`和`Phone`,并使用LINQ查询语法进行分组及筛选。
1201

被折叠的 条评论
为什么被折叠?



