11

我无法通过指定一个值来获取密钥。我可以实现这一目标的最佳方法是什么?

var st1= new List<string> { "NY", "CT", "ME" };
var st2= new List<string> { "KY", "TN", "SC" };
var st3= new List<string> { "TX", "OK", "MO" };
var statesToEmailDictionary = new Dictionary<string, List<string>>();
statesToEmailDictionary.Add("test1@gmail.com", st1);
statesToEmailDictionary.Add("test2@gmail.com", st2);
statesToEmailDictionary.Add("test3@gmail.com", st3);

var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Where(y => y.Contains(state))).Key;
4

7 回答 7

19

from 的返回值FirstOrDefault将是 a KeyValuePair<string, List<string>>,因此要获取密钥,只需使用该Key属性即可。像这样:

var emailAdd = statesToEmailDictionary
    .FirstOrDefault(x => x.Value.Contains(state))
    .Key;

或者,这是查询语法中的等价物:

var emailAdd = 
    (from p in statesToEmailDictionary
     where p.Value.Contains(state)
     select p.Key)
    .FirstOrDefault();
于 2013-05-31T15:20:48.780 回答
2

我想你想要:

var emailAdd = statesToEmailDictionary.FirstOrDefault(x => x.Value.Any(y => y.Contains(state))).Key;
于 2013-05-31T15:28:24.860 回答
2

这个线程中的每个人都没有提到该FirstOrDefault方法只能通过Linq获得:

using System;
using System.Collections.Generic;
// FirstOrDefault is part of the Linq API
using System.Linq;

namespace Foo {
    class Program {
        static void main (string [] args) {
            var d = new Dictionary<string, string> () {
                { "one", "first" },
                { "two", "second" },
                { "three", "third" }
            };
            Console.WriteLine (d.FirstOrDefault (x => x.Value == "second").Key);
        }
    }
}
于 2014-10-16T21:20:29.783 回答
1
var emailAdd = statesToEmailDictionary
    .FirstOrDefault(x => x.Value != null && x.Value.Contains(state))
    .Key;

但是,如果您正在寻找性能,我建议您颠倒您的字典并创建一个字典<state, email>来做您正在寻找的东西。

// To handle when it's not in the results
string emailAdd2 = null;
foreach (var kvp in statesToEmailDictionary)
{
    if (kvp.Value != null && kvp.Value.Contains(state))
    {
        emailAdd2 = kvp.Key;
        break;
    }
}
于 2013-05-31T15:23:13.940 回答
1
var emailAdd = statesToEmailDictionary.First(x=>x.Value.Contains(state)).Key;
于 2014-12-16T07:29:12.553 回答
0

简单的 Linq 就可以做到这一点

Dim mKP = (From mType As KeyValuePair(Of <Key type>, <Value type>) In <Dictionary>
           Where mType.Value = <value seeked> Select mType).ToList

If mKP.Count > 0 then
    Dim value as <value type> = mKP.First.Value
    Dim key as <Key type> = mKP.First.Key 
End if 

当然,如果有重复的值,这将返回多个KeyValuePair

于 2014-11-10T16:08:32.897 回答
-1
var temp = statesToEmailDictionary.Where( x => x.Value.Contains(state)).FirstOrDefault();
var emailAdd = temp != null ? temp.Key : string.Empty;
于 2013-05-31T15:23:58.937 回答