Skip to main content
 首页 » 编程设计

c#之从 C# 集合返回 Dictionarystring, ListItem>> 的 LINQ

2024年02月27日30itcoder

LINQ 专家如何将其转换为 linq。

Public Class Item     
{ 
 
   Public string Name {get;set;}   
 
   Public string Value {get;set;} 
 
   Public bool IsDis {get;set;} 
 
} 

我有这样的收藏

{  
  Name ="ABC", Value="x", IsDis= true 
 
  Name ="ABC", Value="y", IsDis=false 
 
  Name ="ABC1", Value="1",  IsDis false 
 
  Name ="ABC1", Value="2", IsDis= true         
} 

因为 Name 属性具有值列表。所以我必须像这样编写返回

的 LINQ 查询
  Dictionary <string, List<Item>> = collection?????? 

请您参考如下方法:

GroupBy 通过 Name 然后将其收集到 Dictionary 中。

Dictionary<string, List<Item>> resultSet = collection 
                               .GroupBy(e => e.Name) 
                               .ToDictionary(g => g.Key, g => g.ToList());