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

本文关键字:存储 变量 列表 linq 过滤 使用 | 更新日期: 2023-09-27 17:57:36

我得到了一个项目列表,希望根据列的不同值(即基于级别)过滤列表,过滤后还需要获得计数并将其存储为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;            

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

您想将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();