如何使用LINQ对字典中的键列表进行过滤
本文关键字:列表 过滤 何使用 LINQ 字典 | 更新日期: 2023-09-27 18:13:27
我将这个字典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();
}
你可以这样使用
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 ;
您可以通过映射链接您的方式EDITED我错过了一个嵌套级别,他想查询哈希集而不是整个字典
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 ...
section。
你这样称呼它
string[] keys = new string[]{"key1", "key2", ... , "keyN"};
DoStuff(keys, 123);
应该可以