【发布时间】:2019-09-10 14:23:46
【问题描述】:
我有一个类型 A 的列表名称 lstA,其中类型 A 包含类型 B 的列表:
List<A> lstA;
Class A()
{
List<B> lstB;
}
Class B()
{
string str;
}
我想过滤列表 lstA,其中 B 类中的 str 具有某些特定值:
res = lstA.where(x => x.lstB.where(y => y.str == "some_value"));
目前我在 lstA 上使用 foreach 循环解决了这个问题:
foreach (var l in lstA)
{
l.lstB.RemoveAll(x => x.str != "some_value");
}
res = lstA;
但我认为这不是最好的方法。有什么想法吗?
【问题讨论】:
-
“我认为这不是最好的方法” - 为什么不呢?看起来很丑吗?它工作不正确吗?表现不佳吗?
-
没有
res = lstA.where(x => x.lstB.where(y => y.str == "some_value"));然后lstA.lstB = res不起作用?假设您想修改原始列表。 -
hmmm 不清楚你是否想从 lstA 中获取所有 A,其中 lstB 包含 b 其中 b str == 某个值,或者如果你想从 lstB 中删除 != 值(你使用第二个代码)跨度>
-
@Selvin 我想要 lstA 中的所有 A,但只有 str 具有值的 B。
-
@CodeCaster 没有那么优雅。我将修改我的 lstA。
标签: c# where-clause generic-list