获取具有重复项的对象列表C#linq

时间:2015-11-06 09:12:19

标签: c# linq list duplicates

我有一个像这样的对象列表: -

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分组的值。

我有两个字符串即。我希望根据EmployeeName在值组中的不同值(placeStringtimeString)填写TimePlace

这样的事情: -

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

我该如何解决这个问题?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

预期结果是什么?输出所需的结果很容易。只需使用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));});
}