Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用linq过滤后将列表项存储到变量中_C#_Linq_List - Fatal编程技术网

C# 使用linq过滤后将列表项存储到变量中

C# 使用linq过滤后将列表项存储到变量中,c#,linq,list,C#,Linq,List,我得到了一个项目列表,想要根据列的不同值(即基于级别)过滤列表,并且在过滤之后需要获得计数并将其存储为int变量。 谁能帮帮我吗 **List** Public Class Totalitems { public string ItemName; public string ItemId; public string ItemGroup; public int Level; } Id= "123asd"; Li

我得到了一个项目列表,想要根据列的不同值(即基于级别)过滤列表,并且在过滤之后需要获得计数并将其存储为int变量。 谁能帮帮我吗

**List**

   Public Class Totalitems
    {
     public string ItemName;
     public string ItemId;
     public string ItemGroup;
     public int Level;
    } 

    Id= "123asd";

    List<Totalitems> l_items = this.getslist(Id);

       /*How to filter based on distinct level */

      /*  var filteredItems = (
            from p in l_items 
           select p.Level)
            .Distinct();  */                       

    **Finally:**
        //Stores the elements contained in the List into a variable
        int totalItemsafterFiltering = l_FilteredItems.Count;            
**列表**
公共类总计项目
{
公共字符串ItemName;
公共字符串ItemId;
公共字符串项组;
公共智力水平;
} 
Id=“123asd”;
List l_items=this.getslist(Id);
/*如何基于不同级别进行过滤*/
/*变量filteredItems=(
来自l_项中的p
选择p.Level)
.Distinct();*/
**最后:**
//将列表中包含的元素存储到变量中
int totalItemsafterFiltering=l_FilteredItems.Count;

您想使用
GroupBy
执行此任务:

var numberOfDifferentLevels = l_items.GroupBy(x => x.Level).Count();
GroupBy
特别有用,如果您想处理组中的实际元素。例如,您可能想知道每个级别有多少项:

var itemsPerLevel = l_items.GroupBy(x => x.Level)
                           .Select(x => new { Level = x.Key,
                                              NumberOfItems = x.Count() });
当您真正只关心不同级别的数量时,另一种方法是:

var numberOfDifferentLevels = l_items.Select(x => x.Level).Distinct().Count();