简体   繁体   English

如何使用LINQ或Lambda将字典中的过滤值列表获取到列表中?

[英]How to get a list of filtered values in Dictionary into a List using LINQ or Lambda?

I have two Lists: ListA and ListB as well as a Dictionary DictA. 我有两个列表:ListA和ListB以及一个字典DictA。

I am going through all the values of ListA and I want to return the "Value" of DictA into ListB. 我正在遍历ListA的所有值,我想将DictA的“值”返回给ListB。

At the moment I am doing it as follows: 目前,我正在执行以下操作:

ListA = ...
foreach(var x in ListA) {
    if(DictA.ContainsKey(x))
    {
         ListB.add(DictA[x]);
    }
}

How do I do that in Lambda or LINQ? 如何在Lambda或LINQ中做到这一点?

You could do this (a pretty direct translation of your code): 您可以这样做(代码的直接翻译):

ListB.AddRange(ListA.Where(t => DictA.ContainsKey(t)).Select(t => DictA[t]));

If you're sure all ListA values exist in the dictionary, then you can remove the .Where(..) and leave just the .Select(..) . 如果您确定字典中存在所有ListA值,则可以删除.Where(..)并仅保留.Select(..)

If ListB is to contain only these values, then you could re-arrange things slightly: 如果ListB仅包含这些值,那么您可以稍作重新排列:

var ListB = ListA.Where(t => DictA.ContainsKey(t)).Select(t => DictA[t]).ToList();

Alternative method (might be faster): 替代方法(可能会更快):

var ListB = ListA.Intersect(DictA.Keys).Select(t => DictA[t]).ToList();

First of all, if you are not using TryGetValue, then you are doing object search twice, as first ContainsKey and then retrieving object. 首先,如果您没有使用TryGetValue,那么您将进行两次对象搜索,首先是ContainsKey,然后是检索对象。 In terms of best performance, this should be the case. 就最佳性能而言,应该是这种情况。

 var ListB = ListA.Select<TypeA>( x=> { 
              TypeA a = null; 
              DictA.TryGetValue(x, out a);
              return a; }).Where( x=> x != null).ToList();

In above case, you are enumerating your list only once and you are retrieving the item also only once. 在上述情况下,您只枚举列表一次,并且仅检索一次该项目。

You can write an extension method as below to reuse this, 您可以如下编写扩展方法来重复使用此方法,

public static IEnumerable<TValue> ToFilteredValues<TKey,TValue>(
        this IDictionary<TKey,TValue> dict, 
             IEnumerable<TKey> list){
     TValue value;
     foreach(var key in list){
        if(dict.TryGetValue(key, out value))
           yield return value;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM