Linq GroupBy() 和 ToLookup()

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
  public static void Main()
  {
    var list = new List<Product>{
      new Product{ Id=1, Name="Name1", Category="A"},
      new Product{ Id=2, Name="Name2", Category="A"},
      new Product{ Id=3, Name="Name3", Category="B"},
      new Product{ Id=4, Name="Name4", Category="B"},
      new Product{ Id=5, Name="Name5", Category="C"},
    };

    var groups = list.GroupBy(p => p.Category);
    list.RemoveAll(p => p.Category =="B");
    Console.WriteLine(string.Join("-", list.Select(p => p.Name)));
    foreach(var g in groups){
      Console.WriteLine($"{g.Key} : {string.Join("-", g.Select(p => p.Name))}");
    }
Console.WriteLine("*****************************************");
    list = new List<Product>{
      new Product{ Id=1, Name="Name1", Category="A"},
      new Product{ Id=2, Name="Name2", Category="A"},
      new Product{ Id=3, Name="Name3", Category="B"},
      new Product{ Id=4, Name="Name4", Category="B"},
      new Product{ Id=5, Name="Name5", Category="C"},
    };
    var lookup = list.ToLookup(p => p.Category);
    list.RemoveAll(p => p.Category =="B");
    Console.WriteLine(string.Join("-", list.Select(p => p.Name)));
    foreach(var lk in lookup){
      Console.WriteLine($"{lk.Key} : {string.Join("-", lk.Select(p => p.Name))}");
    }
  }

}

public class Product{
  public int Id {get;set;}
  public string Name {get;set;}
  public string Category {get;set;}
}

输出:

Name1-Name2-Name5
A : Name1-Name2
C : Name5
*****************************************
Name1-Name2-Name5
A : Name1-Name2
B : Name3-Name4
C : Name5
可见ToLookup做了深拷贝,没有受延迟加载的影响

Try it!

posted @ 2024-02-05 17:27  Cyber9527  阅读(27)  评论(0编辑  收藏  举报