[英]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.