获取具有重复C#linq的对象列表
本文关键字:对象 列表 C#linq 获取 | 更新日期: 2023-09-27 18:20:53
我有一个对象列表,如下所示:-
List<EmployeeModel> mList = new List<EmployeeModel>();
mList.Add(new EmployeeModel { Place = "place1", Time = time1, EmployeeName = "abc" });
mList.Add(new EmployeeModel { Place = "place2", Time = time2, EmployeeName = "abc" });
mList.Add(new EmployeeModel { Place = "place3", Time = time3, EmployeeName = "abc" });
mList.Add(new EmployeeModel { Place = "place1", Time = time4, EmployeeName = "abc" });
mList.Add(new EmployeeModel { Place = "place2", Time = time5, EmployeeName = "pqr" });
mList.Add(new EmployeeModel { Place = "place3", Time = time6, EmployeeName = "xyz" });
mList.Add(new EmployeeModel { Place = "place1", Time = time7, EmployeeName = "pqr" });
mList.Add(new EmployeeModel { Place = "place2", Time = time8, EmployeeName = "xyz" });
mList.Add(new EmployeeModel { Place = "place3", Time = time9, EmployeeName = "abc" });
我想首先对列表进行排序,以根据EmployeeName查找重复项。我做如下:-
var dupes = mList.GroupBy(x => new { x.EmployeeName }).Where(x => x.Skip(1).Any());
这给了我一组按EmployeeName分组的值。
我有两个字符串,即placeString
和timeString
,我想根据EmployeeName值组中的不同值(Time
和Place
)来填充它们。
大概是这样的:-
EmployeeName - abc
placeString:place1 timeString:time4
placeString:place1 timeString:time2
placeString:place1 timeString:time3
EmployeeName - pqr
placeString:place2 timeString:time5
placeString:place1 timeString:time7
EmployeeName - xyz
placeString:place3 timeString:time6
placeString:place2 timeString:time8
我该如何解决此问题?如有任何帮助,我们将不胜感激。
预期结果是什么?输出您想要的结果很容易。只需使用foreach
:
foreach(var dup in dups)
{
Console.WriteLine(String.Format("EmployeeName - {0}", dup.Key));
foreach(EmployeeModel x in dup)
Console.WriteLine(String.Format("placeString:{0} timeString:{1}", x.Place, x.Time));});
}