【发布时间】:2017-10-26 11:54:00
【问题描述】:
我有一个包含 2 个其他列表的类的列表(实际上是 HashSet)。这是带有示例数据的模型:
public class Example
{
public Example(HashSet<int> a, HashSet<int> b)
{
ListA = a;
ListB = b;
}
public HashSet<int> ListA { get; set; }
public HashSet<int> ListB { get; set; }
}
public class UseCase
{
public UseCase()
{
var hs = new HashSet<Example>();
hs.Add(new Example(new HashSet<int> { 1}, new HashSet<int> { 100, 200 }));
hs.Add(new Example(new HashSet<int> { 2,3,4,5 }, new HashSet<int> { 100, 200, 300 }));
hs.Add(new Example(new HashSet<int> { 6,9,12 }, new HashSet<int> { 200, 300 }));
}
}
以下是两个列表的规则:
List A 只包含唯一的数字——它们从不重复,无论是在它们自己的 HashSet 中还是在任何其他 ListA HashSet 中。
List B 包含在其自己的 HashSet 中唯一的数字,但它们可能在一个或多个 List B HashSet 中重复。
我要做的是返回匹配 ListA 行中的所有数字,其中 ListB 中存在特定数字。
这是一个模拟 linq 查询:
public static IEnumerable<int> GetDistinctFromListA(int b)
{
return UsesCases
.Where(x => x.ListB.Contains(b))
}
所以,此时我有许多行,但我现在需要从匹配的 ListB 列表中提取所有数字。如果输入的参数是 100,那么我希望返回一个包含数字 1、2、3、4 和 5 的列表。
我一直在玩 All 和 SelectMany,但似乎无法得到我需要的结果。
【问题讨论】:
-
什么是用例?
-
hs.Where(x => x.ListB.Contains(100)).SelectMany(x => x.ListA)适合我吗? -->SelectManyIterator { 1, 2, 3, 4, 5 } -
@Patrick - 它只代表我创建的集合 - 它是一个静态 HashSet
,与 UseCase 类中的相同 -
您真的不应该将哈希集称为“列表”。它们不是列表,它们是哈希集。