0

我得到了一个项目列表,想要根据列不同值(即基于级别)过滤列表,并且在过滤后需要获取计数并将它们存储为 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;            
4

1 回答 1

2

您想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();
于 2013-02-05T12:18:42.667 回答