Home > Back-end >  Using LINQ to group a field value into an array based on an ID
Using LINQ to group a field value into an array based on an ID

Time:07-18

I have the following class:

public class LoginGroup
{
  public int LoginID{ get; set; }
  public int GroupID { get; set; }
  public string GroupName{ get; set; }
}

If I have the following list:

{ LoginID = 1, GroupID = 1, GroupName = "Group1"}
{ LoginID = 1, GroupID = 2, GroupName = "Group2"}
{ LoginID = 2, GroupID = 1, GroupName = "Group1"}
{ LoginID = 3, GroupID = 1, GroupName = "Group1"}
{ LoginID = 3, GroupID = 2, GroupName = "Group2"}
{ LoginID = 3, GroupID = 3, GroupName = "Group3"}
{ LoginID = 3, GroupID = 4, GroupName = "Group4"}

and I want to create the following result list:

{LoginID = 1, GroupIDs = [1, 2]}
{LoginID = 2, GroupIDs = [1, 2]}
{LoginID = 3, GroupIDs = [1, 2, 3, 4]}

Is it possible to accomplish all this with one LINQ query?

Currently I'm iterating through every user, populating the array and then deleting the duplicate items with same ID, but it feels like there might be a good solution with LINQ that I'm not aware of.

Thanks.

CodePudding user response:

try this

var result = list
                .GroupBy(n => n.LoginID)
                .Select(r => new { LoginID = r.Key, 
                   GroupIds = r.Select(l => l.GroupID).Distinct().ToArray() })
                .ToList();

//or maybe better

var result = list
                .GroupBy(n => n.LoginID)
                .Select(r => new { LoginID = r.Key, 
                  GroupIds = string.Join(",",r.Select(l => l.GroupID).Distinct()) })
                .ToList();

CodePudding user response:

loginGroups
    .GroupBy(lg => lg.LoginID)
    .Select(group => new { LoginId = group.Key, GroupIDs = group.Select(g => g.GroupID).ToArray() })
    .ToList();
  • Related