[英]Get items from nested list
我有一個包含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 }));
}
}
這是兩個列表的規則:
列表A僅包含唯一編號-在它們自己的HashSet或任何其他ListA HashSet中,它們永遠不會重復。
列表B包含在其自己的HashSet中唯一的數字,但可以在一個或多個列表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,但似乎無法獲得所需的結果。
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; }
}
static IEnumerable<int> GetDistinctFromListA(HashSet<Example> hs, int b)
{
var rv = hs.Aggregate(new HashSet<int>(), (acc, el) =>
{
if (el.ListB.Contains(b)) acc.UnionWith(el.ListA);
return acc;
});
return rv;
}
static void Main(string[] args)
{
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 }));
foreach (var b in hs.SelectMany(e => e.ListB).Distinct())
Console.WriteLine($"{b} => {string.Join(",", GetDistinctFromListA(hs, b))}");
Console.ReadLine();
}
這遍歷了hs的所有元素,檢查每個元素ListB是否包含b,如果包含b,則將其ListA元素添加到結果中。
如果僅比較哈希集而不依賴其他哈希集,則可以使用“相交” /“聯合” /“除外”等(設置理論的東西)。
HashSet
只能包含唯一值,也就是說,您進行的所有查詢本質上都返回不同的值。 如果要查找兩個HashSet
之間的交集,則可以調用Intersect
方法。
例如:
//The additional 1 is ignored here
HashSet<int> A = new HashSet<int> { 1, 1, 2, 3, 4, 5 };
HashSet<int> B = new HashSet<int> { 1, 5, 8, 9 };
var Result = A.Intersect(B);
我想你要歸還2套的交集
有一個Linq函數可以做到這一點
var commonInBoth = List1.Intersect(List2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.