Using LINQ to group a list of objects

前端 未结 5 1919
攒了一身酷
攒了一身酷 2020-12-08 14:34

I have an object:

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


        
5条回答
  •  不知归路
    2020-12-08 15:12

    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. If so you should design your class Customer differently, like this:

    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();
    

提交回复
热议问题