2010-04-14 13 views
140

Ho un metodo che restituisce un IEnumerable<KeyValuePair<string, ArrayList>>, ma alcuni chiamanti richiedono che il risultato del metodo sia un dizionario. Come posso convertire lo IEnumerable<KeyValuePair<string, ArrayList>> in un Dictionary<string, ArrayList> in modo da poter utilizzare TryGetValue?Ricreazione di un dizionario da un oggetto IEnumerable <KeyValuePair <>>

metodo:

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

chiamante:

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

Eventuali duplicati? http://stackoverflow.com/questions/7850334/how-to-convert-ienumerable-of-keyvaluepairx-y-to-dictionary – Coolkau

risposta

263

Se si sta utilizzando .NET 3.5 o .NET 4, è facile creare il dizionario con LINQ:

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

Non esiste un IEnumerable<T1, T2> ma un KeyValuePair<TKey, TValue> va bene.

+9

Penseresti che ci sarebbe una chiamata che non richiede argomenti, dato quel dizionario < TKey, TValue> implementa IEnumerable >, ma vabbè. Abbastanza facile da crearne uno tuo. – Casey

+1

@emodendroket perché lo penseresti? Puoi trasmettere il dizionario direttamente a IEnumerable menzionato a causa dell'interfaccia, ma non viceversa. Ad esempio, IEnumerable > 'non implementa o eredita' Dictionary '. – djv

+4

@DanVerdolino Lo so. Lo penseresti perché è come una delle cose più comuni che potresti voler fare con un IEnumerable di KVP. – Casey

-27

Creazione di un oggetto Dictionary da Databile utilizzando 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; 
    } 
} 
Problemi correlati