如何使用Linq筛选嵌套列表?
我在如何使用Linq筛选嵌套列表?,linq,linq-to-objects,Linq,Linq To Objects,我在字典上使用LINQ,如下所示: var searchCategories = new List {"A", "B", "C"}; Result = CategoryMapper.Mapping.Where( x => searchCategories.Contains(x.Key)). Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
字典上使用LINQ,如下所示:
var searchCategories = new List {"A", "B", "C"};
Result = CategoryMapper.Mapping.Where(
x => searchCategories.Contains(x.Key)).
Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
var searchCategories=新列表{“A”、“B”、“C”};
结果=CategoryMapper.Mapping.Where(
x=>searchCategories.Contains(x.Key))。
选择(x=>newtuple(x.Key,x.Value)).ToList();
这将返回类别A、B或C中的所有ID。然而,我想做的是检索类别A、B和C中的ID
我很难弄清楚如何与Linq合作
更新
很抱歉,我应该在我的第一篇文章中添加更多的信息。我字典中的列表看起来有点像这样(我这里只使用数字来简化):
答:{1,2,3}
B:{1,3}
C:{3}
因此,在本例中,我希望查询结果为“3”,因为它是唯一具有所有类别的数字。您可以尝试将x=>searchCategories.Contains(x.Key)
更改为x=>searchCategories.all(c=>x.Key.Contains(c))
,也就是说,最后的代码片段应该是
var searchCategories = new List<string> {"A", "B", "C"};
Result = CategoryMapper.Mapping.Where(
x => searchCategories.All(c => x.Key.Contains(c))).
Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
var searchCategories=新列表{“A”、“B”、“C”};
结果=CategoryMapper.Mapping.Where(
x=>searchCategories.All(c=>x.Key.Contains(c)))。
选择(x=>newtuple(x.Key,x.Value)).ToList();
您可以尝试将x=>searchCategories.Contains(x.Key)
更改为x=>searchCategories.All(c=>x.Key.Contains(c))
,即最后的代码段应该是
var searchCategories = new List<string> {"A", "B", "C"};
Result = CategoryMapper.Mapping.Where(
x => searchCategories.All(c => x.Key.Contains(c))).
Select(x => new Tuple<string, IList<ID>>(x.Key, x.Value)).ToList();
var searchCategories=新列表{“A”、“B”、“C”};
结果=CategoryMapper.Mapping.Where(
x=>searchCategories.All(c=>x.Key.Contains(c)))。
选择(x=>newtuple(x.Key,x.Value)).ToList();
要获取所有ID,SelectMany
方法非常适合:
var ids = CategoryMapper.Mapping.SelectMany(kv => kv.Value);
要获取所有ID,SelectMany
方法非常适合:
var ids = CategoryMapper.Mapping.SelectMany(kv => kv.Value);
看起来你只是在所有列表的交叉点上。这应该很容易获得
var searchCategories = new HashSet<string> { "A", "B", "C" };
var result = CategoryMapper.Mapping
.Where(map => searchCategories.Contains(map.Key))
.Select(map => map.Value as IEnumerable<ID>)
.Aggregate((acc, cur) => acc.Intersect(cur));
看起来你只是在所有列表的交叉点上。这应该很容易获得
var searchCategories = new HashSet<string> { "A", "B", "C" };
var result = CategoryMapper.Mapping
.Where(map => searchCategories.Contains(map.Key))
.Select(map => map.Value as IEnumerable<ID>)
.Aggregate((acc, cur) => acc.Intersect(cur));
只是贴了出来,回答了,删除了,因为我误读了你的问题。很抱歉搞混了。请忽略。只是张贴和回答,并删除它,因为我误读了你的问题。很抱歉搞混了。请忽略。