Recreating a Dictionary from an IEnumerable<KeyValuePair<>>

徘徊边缘 提交于 2019-11-26 12:38:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!