![](/img/trans.png)
[英]What is the best way to convert dictionary to a custom KeyValuePair type list?
[英]best way to receive a list of objects from list of KeyValuePair?
我有一個KeyValuePairs列表,我想根據鍵值對其進行過濾,因此最終我將獲得一個經過過濾的值列表(即-將不包含原始列表中的所有值)。
我猜也許最好的方法是某種形式的Lambda表達式,但我不確定如何實現。 謝謝阿隆
嘗試這個:
var values = list.Where(x => x.Key == "whatever").Select(x => x.Value);
這將僅為您提供值的過濾列表。
顯然,您可以更改過濾鍵的方式。
使用以下內容:
var filteredList = list.Where(x => x.Key == "Key");
您正在尋找LINQ擴展方法的某種組合(具體取決於您要嘗試執行的操作)。
例如,如果我有一個顏色列表的水果,並想要收集紅色水果的集合,則可以執行以下操作:
var fruits = new List<KeyValuePair<string,string>>() {
new KeyValuePair<string,string>("Apple", "Green"),
new KeyValuePair<string,string>("Orange", "Orange"),
new KeyValuePair<string,string>("Strawberry", "Red"),
new KeyValuePair<string,string>("Cherry", "Red")
};
var redFruits = fruits.Where(kvp => kvp.Value == "Red").Select(kvp => kvp.Key);
// this would result in a IEnumberable<string> { "Strawberry", "Cherry" }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.