基于另一个列表C#的子元素过滤列表 [英] Filtering list based on child element of another list C#
本文介绍了基于另一个列表C#的子元素过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的结构类似于
i have structure like
public class Categories {
Public List<categorydescription> LisstOfcategories {get ; set;}
}
public class categoryDescription {
public string CategoryCode {get ;set;}
}
我有字符串列表,其中包含一些类别,例如
And i have List of string which contains some categories like
List<string> lst = new List<string>();
lst.Add("CategoryCode1");
lst.Add("CategoryCode2");
和List类别为
and List of Categories as
List<Categories > lstCategories Now how do i filter lstCategoriessuch that CategoryCode having same value defined in lst collection should not be selected in Linq C# ? How can i filter this ?
我的尝试:
What I have tried:
i want to query through LINQ, i have tried following which does not compile lstCategories= lstCategories.Where(x => lst.Any(y => y != x.categoryDescription.ForEach(z => z.CategoryCode)));
推荐答案
首先,你的模型(结构)是错误的!
我建议用这种方式创建Category对象:
First of all, your model (structure) is wrong!
I'd suggest to create Category object this way:
public class Category
{
private string sdescription = string.Empty;
private string scode = string.Empty;
public Category(string _description)
{
sdescription = _description;
}
public Category(string _description, string _code)
{
sdescription = _description;
scode = _code;
}
public string Description
{
get { return sdescription; }
set { sdescription = value; }
}
public string Code
{
get { return scode; }
set { scode = value; }
}
}
现在,您的列表可能如下所示:
Now, your list could look like:
List<Category> Categories = new List<Category>()
{
new Category("Books", "001"),
new Category("Cars", "002"),
new Category("Tools", "003")
};
另一个类别列表(CategoryCode):
And another list of categories (CategoryCode):
List<string> lst = new List<string>()
{
"Cars",
"Dogs"
};
Finall查询:
Finall query:
var CategoriesNotOnLst = Categories
.Where(x => !lst.Any(z => x.Description==z))
.ToList();
结果:
Result:
Description Code
Books 001
Tools 003
您可以通过以下方式实现:
You can achieve it by following way:
lstCategories.Where(x => lst.Contains(x.CategoryCode));
这篇关于基于另一个列表C#的子元素过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文