简体   繁体   English

使用 LINQ 对对象列表进行分组

[英]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我想返回一个 linq 查询,它看起来像

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 使用 Linq 将对象列表分组为新的对象列表分组列表

code代码

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

works but does not give the desired output.有效,但没有提供所需的输出。

var groupedCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                      .Select(grp =>new { GroupID =grp.Key, CustomerList = grp.ToList()})
                                      .ToList();
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:如果你不想改变原始数据,你应该像这样向你的类添加一些方法(一种克隆和修改):

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data.我认为您可能希望在不修改原始数据的情况下以不同的方式显示Customer If so you should design your class Customer differently, like this:如果是这样,您应该以不同的方式设计您的类Customer ,如下所示:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

这是你想要的吗?

var grouped = CustomerList.GroupBy(m => m.GroupID).Select((n) => new { GroupId = n.Key, Items = n.ToList() });
var result = from cx in CustomerList
         group cx by cx.GroupID into cxGroup
     orderby cxGroup.Key
     select cxGroup; 

foreach (var cxGroup in result) { 
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key)); 
  foreach (var cx in cxGroup) { 
    Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}", 
      new object[] { cx.ID, cx.Name, cx.GroupID })); 
  }
}

The desired result can be obtained using IGrouping , which represents a collection of objects that have a common key in this case a GroupID可以使用IGrouping获得所需的结果,它表示具有公共键的对象集合,在这种情况下为GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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