简体   繁体   中英

Get List of objects with duplicates C# linq

I have a list of objects like so :-

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" });

I want to sort the list first to find the duplicates based on the EmployeeName. Which I do as follows:-

var dupes = mList.GroupBy(x => new { x.EmployeeName }).Where(x => x.Skip(1).Any());

This gives me a group of values grouped by EmployeeName.

I have two strings ie. placeString and timeString which I want to fill in according to the different values ( Time and Place ) in the group of values by EmployeeName.

Something like so:-

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

How do I solve this? Any help would be appreciated.

What is the expected result? It's easy to output your desired result. Just use a 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));});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM