[英]Get a list of elements, from a sortedlist, using a list of keys, using LINQ, in C#
帶有排序列表:
[11] = "a"
[22] = "b"
[35] = "c"
[40] = "d"
[45] = "e"
以及鍵列表:
[35, 40, 45]
如何獲得與鍵列表匹配的數據。 輸出應為:
["c", "d", "e"]
編輯:
類型是SortedList(),類“ SomeClass”也包含鍵值。 一個例子是:
class SomeClass
{
string Key;
... some other fields
}
我的嘗試是:
MyList.Values.Where(_ => keys.Contains(_.key)).ToList();
但這沒有使用索引。
只要可以找到所有元素,此方法就起作用:
public class A
{
public string Key;
public string SomeValue;
}
var l = new SortedList<string, A>
{
["aa"] = new A { Key = "aa" },
["bb"] = new A { Key = "bb" },
["cc"] = new A { Key = "cc" },
["dd"] = new A { Key = "dd" }
};
var ids = new List<string> { "bb", "cc" };
var r = ids.Select(i => l[i]).ToList();
遵循使用TryGetValue的建議是好的,但是我不確定如何將其與select結合使用。
根據SortedList
的大小和ids
的大小,下面的代碼可能值得考慮(以避免迭代整個SortedList
)。 如果ids
小而list
大,則將特別有益。
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp12
{
public class Program
{
public static void Main(string[] args)
{
var list = new SortedList<string, SomeClass>
{
["aa"] = new SomeClass { Key = "aa" },
["bb"] = new SomeClass { Key = "bb" },
["cc"] = new SomeClass { Key = "cc" },
["dd"] = new SomeClass { Key = "dd" }
};
var ids = new List<string> { "bb", "cc" };
var results = ids.Select(x =>
{
list.TryGetValue(x, out var matching);
return matching;
}).Where(z => z != null);
// Output to show the results
Console.WriteLine(string.Join(",", results.Select(z => z.Key)));
}
}
}
那么,這行得通嗎?
var list = new SortedList<string, SomeClass>
{
["aa"] = new SomeClass { Key = "aa" },
["bb"] = new SomeClass { Key = "bb" },
["cc"] = new SomeClass { Key = "cc" },
["dd"] = new SomeClass { Key = "dd" }
};
var ids = new List<string> { "bb", "cc" };
var results = list.Where(x => ids.Contains(x.Key)).ToList();
如果只需要SomeClass
列表:
var someClassList = list.Where(x => ids.Contains(x.Key)).Select(y => y.Value);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.