我有一个返回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");
答案 0 :(得分:294)
如果您使用的是.NET 3.5或.NET 4,则可以使用LINQ轻松创建字典:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
没有IEnumerable<T1, T2>
,但KeyValuePair<TKey, TValue>
没问题。
答案 1 :(得分:4)
从.NET Core 2.0开始,构造函数Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
现在存在。
答案 2 :(得分:-33)
使用IEnumerable从Datatable创建Dictionary对象
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;
}
}