Recreating a Dictionary from an IEnumerable<KeyValuePair>Keep Where() consistent for DictionaryHow can I cast IEnumerable to Dictionary?How to convert IEnumerable of KeyValuePair<x, y> to Dictionary?difference between IEnumerable vs Dictionary C#How do I cast this type into a Dictionary?Comparing Two ListsHow to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryReturning IEnumerable<T> vs. IQueryable<T>Iterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?Why not inherit from List<T>?

Using credit/debit card details vs swiping a card in a payment (credit card) terminal

Why did David Cameron offer a referendum on the European Union?

What is a Centaur Thief's climbing speed?

Did people Unsnap to where they were?

My employer faked my resume to acquire projects

Can a person survive on blood in place of water?

Is DateWithin30Days(Date 1, Date 2) an Apex Method?

Which melee weapons have the Two-Handed property, but lack Heavy and Special?

what kind of chord progession is this?

Is real public IP Address hidden when using a system wide proxy in Windows 10?

Is Jon Snow the last of his House?

using Leibniz rule to solve definite integral

Grammar Question Regarding "Are the" or "Is the" When Referring to Something that May or May not be Plural

How did these characters "suit up" so quickly?

Did 20% of US soldiers in Vietnam use heroin, 95% of whom quit afterwards?

Caught 2 students cheating together on the final exam that I proctored

Can I tell a prospective employee that everyone in the team is leaving?

Count rotary dial pulses in a phone number (including letters)

Looking for a soft substance that doesn't dissolve underwater

What are these arcade games in Ghostbusters 1984?

Could a 19.25mm revolver actually exist?

Why do most published works in medical imaging try to reduce false positives?

I know that there is a preselected candidate for a position to be filled at my department. What should I do?

Any advice on creating fictional locations in real places when writing historical fiction?



Recreating a Dictionary from an IEnumerable>


Keep Where() consistent for DictionaryHow can I cast IEnumerable to Dictionary?How to convert IEnumerable of KeyValuePair<x, y> to Dictionary?difference between IEnumerable vs Dictionary C#How do I cast this type into a Dictionary?Comparing Two ListsHow to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?What is the best way to iterate over a dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryReturning IEnumerable<T> vs. IQueryable<T>Iterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?Why not inherit from List<T>?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








155















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");









share|improve this question
























  • Possible duplicate? stackoverflow.com/questions/7850334/…

    – Coolkau
    Oct 18 '16 at 10:13

















155















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");









share|improve this question
























  • Possible duplicate? stackoverflow.com/questions/7850334/…

    – Coolkau
    Oct 18 '16 at 10:13













155












155








155


15






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");









share|improve this question
















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");






c# collections dictionary ienumerable idictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 13 '15 at 9:18









BartoszKP

27.3k1073109




27.3k1073109










asked Apr 14 '10 at 10:31









learnerplateslearnerplates

1,78641737




1,78641737












  • Possible duplicate? stackoverflow.com/questions/7850334/…

    – Coolkau
    Oct 18 '16 at 10:13

















  • Possible duplicate? stackoverflow.com/questions/7850334/…

    – Coolkau
    Oct 18 '16 at 10:13
















Possible duplicate? stackoverflow.com/questions/7850334/…

– Coolkau
Oct 18 '16 at 10:13





Possible duplicate? stackoverflow.com/questions/7850334/…

– Coolkau
Oct 18 '16 at 10:13












2 Answers
2






active

oldest

votes


















291














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.






share|improve this answer




















  • 10





    You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

    – Casey
    Apr 8 '14 at 21:00






  • 1





    @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

    – djv
    Jul 1 '14 at 15:40






  • 5





    @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

    – Casey
    Jul 1 '14 at 15:42






  • 14





    2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

    – die maus
    Sep 3 '16 at 15:46






  • 4





    It's 2017 now, and we can add this as an extension method!

    – Chris Bush
    May 10 '17 at 21:39


















-32














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;
}
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2636603%2frecreating-a-dictionary-from-an-ienumerablekeyvaluepair%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    291














    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.






    share|improve this answer




















    • 10





      You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

      – Casey
      Apr 8 '14 at 21:00






    • 1





      @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

      – djv
      Jul 1 '14 at 15:40






    • 5





      @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

      – Casey
      Jul 1 '14 at 15:42






    • 14





      2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

      – die maus
      Sep 3 '16 at 15:46






    • 4





      It's 2017 now, and we can add this as an extension method!

      – Chris Bush
      May 10 '17 at 21:39















    291














    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.






    share|improve this answer




















    • 10





      You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

      – Casey
      Apr 8 '14 at 21:00






    • 1





      @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

      – djv
      Jul 1 '14 at 15:40






    • 5





      @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

      – Casey
      Jul 1 '14 at 15:42






    • 14





      2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

      – die maus
      Sep 3 '16 at 15:46






    • 4





      It's 2017 now, and we can add this as an extension method!

      – Chris Bush
      May 10 '17 at 21:39













    291












    291








    291







    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Aug 30 '13 at 22:52









    Roy Tinker

    9,33433550




    9,33433550










    answered Apr 14 '10 at 10:35









    Jon SkeetJon Skeet

    1107k70480538512




    1107k70480538512







    • 10





      You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

      – Casey
      Apr 8 '14 at 21:00






    • 1





      @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

      – djv
      Jul 1 '14 at 15:40






    • 5





      @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

      – Casey
      Jul 1 '14 at 15:42






    • 14





      2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

      – die maus
      Sep 3 '16 at 15:46






    • 4





      It's 2017 now, and we can add this as an extension method!

      – Chris Bush
      May 10 '17 at 21:39












    • 10





      You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

      – Casey
      Apr 8 '14 at 21:00






    • 1





      @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

      – djv
      Jul 1 '14 at 15:40






    • 5





      @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

      – Casey
      Jul 1 '14 at 15:42






    • 14





      2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

      – die maus
      Sep 3 '16 at 15:46






    • 4





      It's 2017 now, and we can add this as an extension method!

      – Chris Bush
      May 10 '17 at 21:39







    10




    10





    You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

    – Casey
    Apr 8 '14 at 21:00





    You'd think there would be a call that doesn't require arguments, given that Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>, but oh well. Easy enough to make your own.

    – Casey
    Apr 8 '14 at 21:00




    1




    1





    @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

    – djv
    Jul 1 '14 at 15:40





    @emodendroket why would you think that? You can cast the Dictionary directly to the IEnumerable mentioned because of the interface, but not the other way around. i.e. IEnumerable<KeyValuePair<TKey, TValue>> does not implement or inherit Dictionary<TKey, TValue>.

    – djv
    Jul 1 '14 at 15:40




    5




    5





    @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

    – Casey
    Jul 1 '14 at 15:42





    @DanVerdolino I know that. You'd think that because it's like one of the most common things you might want to do with an IEnumerable of KVPs.

    – Casey
    Jul 1 '14 at 15:42




    14




    14





    2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

    – die maus
    Sep 3 '16 at 15:46





    2016 now, and I still had to google this. You'd think that there would be a constructor for Dictionary that took a IEnumerable<KeyValuePair<TKey, TValue>> just like List<T> takes a IEnumerable<T>. Also there is no AddRange or even Add that takes key/value pairs. What's up with that?

    – die maus
    Sep 3 '16 at 15:46




    4




    4





    It's 2017 now, and we can add this as an extension method!

    – Chris Bush
    May 10 '17 at 21:39





    It's 2017 now, and we can add this as an extension method!

    – Chris Bush
    May 10 '17 at 21:39













    -32














    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;
    }
    }





    share|improve this answer





























      -32














      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;
      }
      }





      share|improve this answer



























        -32












        -32








        -32







        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;
        }
        }





        share|improve this answer















        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;
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Aug 1 '12 at 3:53









        Habib

        185k23322365




        185k23322365










        answered Jun 5 '11 at 2:14









        Pankaj AwasthiPankaj Awasthi

        92




        92



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2636603%2frecreating-a-dictionary-from-an-ienumerablekeyvaluepair%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현