首页 > 解决方案 > LINQ 查询为正确的键值对使用正确的键

问题描述

我有一个列表属性,它们是这样定义的

class Attribute 
{
   public string Name {get; set;}
   public KeyValuePair<string, object>
}

和存储在 a 中的密钥列表IList<string> listOfKeys

我想将所有值存储在对象列表中,但是如何使用 linq 查询解析正确的键,并提取值并将它们存储到list<object>

到目前为止我尝试过的东西就像

List<attribute> attributes;

some init stuff 

attributes.Where(x => x.Key). 

如何在这里使用我的钥匙?

标签: c#linq

解决方案


尝试使用以下组合Any

IList<string> listOfKeys = new List<string>();
var attributes =  new List<Attribute>();            
attributes.Where(a => listOfKeys.Any(l => a.Foo.Key == l));

Attribute类:

class Attribute
{
    public string Name { get; set; }
    public KeyValuePair<string, object>  Foo { get; set; }
}

更新:

如果你想得到IEnumerable<object>

var result = attributes.Where(a => listOfKeys.Any(l => a.Foo.Key == l))
    .Select(s => s.Foo.Value);

推荐阅读