使用lambda表达式在字典中选择布尔表达式

时间:2012-03-07 19:49:43

标签: .net collections .net-3.5 dictionary lambda

我有一个这样的词典。

public static Dictionary<int?, List<int?>> pegMap = new Dictionary<int?, List<int?>>();

现在我正在尝试检查字典中的列表是否包含某些值,其中字典键是某个值。

if (pegMap.Select(y => y.Value.Contains(disc)).Where(x => x.Equals(key)))
{
    peg = (int)key;
}

但是编译器很生气并且给我一个错误 -

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<bool>' to 'bool'

我在这里做错了什么。请帮忙。

3 个答案:

答案 0 :(得分:2)

听起来你完全无视你正在使用字典的事实。听起来你可能想要:

public bool CheckMap(int? key, int? checkValue)
{
    List<int?> values;
    if (!pegMap.TryGetValue(key, out values))
    {
        return false;
    }
    return values.Contains(checkValue);
}

答案 1 :(得分:1)

Where会返回一个集合,而是要检查是否有Any值满足x.Equals(key)

Dictionary<int?, List<int?>> pegMap = new Dictionary<int?, List<int?>>()
{
    { 1, new List<int?> {1,2,3} },
    { 2, new List<int?> {4,5,6} },
    { 3, new List<int?> {1,4,5} },
    { 4, new List<int?> {6,7,8} },
};

int? key = 2;
int? value = 4;

if (pegMap.Where(p => p.Key == key).Any(p => p.Value.Any(v => v == value)))
{ 
   // returns true;
}

// You can also use
bool result = pegMap.ContainsKey(key) && pegMap[key].Contains(value);

答案 2 :(得分:1)

我认为Jon Skeet的回答效率更高,但如果lambda比其他任何东西都重要(喘气),你可以试试

pegMap.Any(x => x.Key == key && x.Value.Contains(disc))
相关问题