从IEnumerable <KeyValuePair <>>重新创build一个字典

我有一个方法返回一个IEnumerable<KeyValuePair<string, ArrayList>> ,但一些调用者要求方法的结果是一个字典。 如何将IEnumerable<KeyValuePair<string, ArrayList>>转换为Dictionary<string, ArrayList>以便我可以使用TryGetValue

方法:

 public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents() { // ... yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation); } 

呼叫者:

 Dictionary<string, ArrayList> actual = target.GetComponents(); actual.ContainsKey("something"); 

如果您使用.NET 3.5或.NET 4,使用LINQ创build字典很容易:

 Dictionary<string, ArrayList> result = target.GetComponents() .ToDictionary(x => x.Key, x => x.Value); 

IEnumerable<T1, T2>但是KeyValuePair<TKey, TValue>没有问题。

使用IEnumerable从Datable创buildDictionary对象

 using System.Data; using .. public class SomeClass { //define other properties // ... public Dictionary<string, User> ConvertToDictionaryFromDataTable(DataTable myTable, string keyColumnName) { // define IEnumerable having one argument of KeyValuePair IEnumerable<KeyValuePair<string,User>> tableEnumerator = myTable.AsEnumerable().Select(row => { // return key value pair return new KeyValuePair<string,User>(row[keyColumnName].ToString(), new User { UserID=row["userId"].ToString(), Username=row["userName"].ToString(), Email=row["email"].ToString(), RoleName=row["roleName"].ToString(), LastActivityDate=Convert.ToDateTime(row["lastActivityDate"]), CreateDate=Convert.ToDateTime(row["createDate"]), LastLoginDate=Convert.ToDateTime(row["lastLoginDate"]), IsActive=Convert.ToBoolean(row["isActive"]), IsLockedOut=Convert.ToBoolean(row["isLockedOut"]), IsApproved=Convert.ToBoolean(row["isApproved"]) }); }); return tableEnumerator.ToDictionary(x => x.Key, x => x.Value); } } public class User { public string UserID { get; set; } public string Username { get; set; } public string Email { get; set; } public string RoleName { get; set; } public DateTime LastActivityDate { get; set; } public DateTime CreateDate { get; set; } public DateTime LastLoginDate { get; set; } public bool IsActive { get; set; } public bool IsLockedOut { get; set; } public bool IsApproved { get; set; } // Other methods to follow.. } IEnumerable<KeyValuePair<string,User>> ieUsers = membershipUsers.AsEnumerable().Select(row => { return new KeyValuePair<string,User>(row.UserName.ToString(), new User { Username = row.UserName.ToString(), Email = row.Email.ToString() }); }); allMembershipUsers = ieUsers.ToDictionary(x => x.Key, x => x.Value); return allMembershipUsers; } }