[英]How to filter on a list of keys in a Dictionary using LINQ
我将此字典mappings
声明为Dictionary<string, HashSet<string>>
。
我也有这种方法可以对字典中的哈希集执行操作:
public void DoStuff(string key, int iClassId){
foreach (var classEntry in
from c in mappings[key]
where c.StartsWith(iClassId + "(")
select c)
{
DoStuffWithEntry(classEntry);
}
}
private void DoStuffWithEntry(string classEntry){
// Do stuff with classEntry here
}
在一种情况下,我需要对映射字典中的多个键执行此操作,并且我认为最好对键列表进行重写和过滤,而不是为每个键调用DoStuff
来优化执行。
目前,我这样做:
DoStuff("key1", 123);
DoStuff("key2", 123);
DoStuff("key4", 123);
DoStuff("key7", 123);
DoStuff("key11", 123);
逻辑上是这样的,而不是每个都调用DoStuff(FilterOnKeys不是方法-就是我想要的...):
foreach (var classEntry in
from c in mappings.FilterOnKeys("key1", "key2", "key4", "key7", "key11")
where c.StartsWith(iClassId + "(")
select c)
{
DoStuffWithEntry(classEntry);
}
听起来像您想要的:
string[] keys = { "key1", "key2", ... }
var query = from key in keys
from c in mappings[key]
...;
foreach (var entry in query)
{
...
}
(为了便于阅读,我个人会为查询使用一个单独的变量-我不太希望foreach
循环的声明位变得越来越大。)
我根据您的要求使用LINQ
var temp = eid.Select(i =>
EmployeeList.ContainsKey(i)
? EmployeeList[i]
: null
).Where(i => i != null).ToList();
完整的C#源代码为
public class Person
{
public int EmpID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string Gender { get; set; }
}
void Main()
{
Dictionary<int, Person> EmployeeList = new Dictionary<int, Person>();
EmployeeList.Add(1, new Person() {EmpID = 1, Name = "Peter", Department = "Development",Gender = "Male"});
EmployeeList.Add(2, new Person() {EmpID = 2, Name = "Emma Watson", Department = "Development",Gender = "Female"});
EmployeeList.Add(3, new Person() {EmpID = 3, Name = "Raj", Department = "Development",Gender = "Male"});
EmployeeList.Add(4, new Person() {EmpID = 4, Name = "Kaliya", Department = "Development",Gender = "Male"});
EmployeeList.Add(5, new Person() {EmpID = 5, Name = "Keerthi", Department = "Development",Gender = "Female"});
List<int> eid = new List<int>() { 1,3 };
List<Person> SelectedEmployeeList = new List<Person>();
var temp = eid.Select(i =>
EmployeeList.ContainsKey(i)
? EmployeeList[i]
: null
).Where(i => i != null).ToList();
}
您可以通过映射来限制自己的方式编辑我错过了嵌套级别,他想查询哈希集而不是整个字典
public void DoStuff(IEnumerable<string> key, int iClassId)
{
mappings.Where(i=>key.Contains(i.Key)).ToList().ForEach(obj=>
{
foreach (var classEntry in
from c in obj.Value
where c.StartsWith(iClassId + "(")
select c)
{
DoStuffWithEntry(classEntry);
}
}
更改了key
参数,并from c ...
部分更改了。
你这样称呼它
string[] keys = new string[]{"key1", "key2", ... , "keyN"};
DoStuff(keys, 123);
这应该工作
你可以使用这样的东西
var ids = {1, 2, 3};
var query = from item in context.items
where ids.Contains(item.id )
select item;
在你的情况下
string[] keys = { "key1", "key2", ... }
var query = from key in keys
where ids.Contains(keys )
select key ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.