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