Gaurav Gaurav - 3 months ago 12
C# Question

Group By struct list on multiple columns in C#

I am having a struct as

public struct structMailJob
public string ID;
public string MailID;
public int ResendCount;
public int PageCount;

and a list as

List<structMailJob> myStructList = new List<structMailJob>();

I have loaded data in myStructList from database and want myStructList data in a new list after grouping by MailID and ResendCount.

I am trying as:

List<structMailJob> newStructList = new List<structMailJob>();

newStructList = myStructList.GroupBy(u => u.MailID, u=>u.ResendCount)
.Select(grp => new { myStructList = grp.ToList() })

but unable to do that as getting error message - cant implicitly convert generic list to structMailJob.


Linq Query is completely incorrect, following are the important points:

myStructList.GroupBy(u => u.MailID, u=>u.ResendCount) // Incorrect grouping

myStructList.GroupBy(u => new {u.MailID, u.ResendCount }) // Correct grouping, which will do by two columns MailID and ResendCount, last one was only doing by MailID and was using ResendCount for result projection

Now the result is of type IEnumerable<IGrouping<AnonymousType,structMailJob>>, so when you do something like Select, it will end up creating Concatenated List of type IEnumerable<List<structMailJob>> (Removed the assignment to myStructList inside the Select, as that was not correct):

.Select(grp => grp.ToList())

Correct code would require you to flatten using SelectMany as follows:

newStructList = myStructList.GroupBy(u => new {u.MailID, u.ResendCount})
                                      .SelectMany(grp => grp.ToList()).ToList();

Assign it to newStructList, but this code has little use, since literally newStructList is exactly same as myStructList post flattening, ideally you shall be able to use the grouping, so that you can get a subset and thus the correct result, however that depends on your business logic