问题
I have a method that returns an IEnumerable<KeyValuePair<string, ArrayList>>
, but some of the callers require the result of the method to be a dictionary. How can I convert the IEnumerable<KeyValuePair<string, ArrayList>>
into a Dictionary<string, ArrayList>
so that I can use TryGetValue
?
method:
public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents()
{
// ...
yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation);
}
caller:
Dictionary<string, ArrayList> actual = target.GetComponents();
actual.ContainsKey(\"something\");
回答1:
If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
回答2:
Creating a Dictionary object from Datable using IEnumerable
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;
}
}
来源:https://stackoverflow.com/questions/2636603/recreating-a-dictionary-from-an-ienumerablekeyvaluepair