Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - Using LINQ to group a list of objects

I have an object:

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int GroupID { get; set; }
}

I return a list that may look like the following:

List<Customer> CustomerList = new List<Customer>();
CustomerList.Add( new Customer { ID = 1, Name = "One", GroupID = 1 } );
CustomerList.Add( new Customer { ID = 2, Name = "Two", GroupID = 1 } );
CustomerList.Add( new Customer { ID = 3, Name = "Three", GroupID = 2 } );
CustomerList.Add( new Customer { ID = 4, Name = "Four", GroupID = 1 } );
CustomerList.Add( new Customer { ID = 5, Name = "Five", GroupID = 3 } );
CustomerList.Add( new Customer { ID = 6, Name = "Six", GroupID = 3 } );

I want to return a linq query which will look like

CustomerList
  GroupID =1
    UserID = 1, UserName = "UserOne", GroupID = 1
    UserID = 2, UserName = "UserTwo", GroupID = 1
    UserID = 4, UserName = "UserFour", GroupID = 1
  GroupID =2
    UserID = 3, UserName = "UserThree", GroupID = 2
  GroupID =3
    UserID = 5, UserName = "UserFive", GroupID = 3
    UserID = 6, UserName = "UserSix",

I tried from

Using Linq to group a list of objects into a new grouped list of list of objects

code

var groupedCustomerList = CustomerList
  .GroupBy(u => u.GroupID)
  .Select(grp => grp.ToList())
  .ToList();

works but does not give the desired output.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var groupedCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                      .Select(grp =>new { GroupID =grp.Key, CustomerList = grp.ToList()})
                                      .ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...