Populate Dictionary from database using LINQ

Last post 09-25-2009 12:51 PM by mendhak. 1 replies.

Sort Posts:

  • Populate Dictionary from database using LINQ

    09-25-2009, 7:58 AM
    • Member
      355 point Member
    • k000der
    • Member since 02-21-2006, 1:17 PM
    • Posts 206

    I have been trying to figure out how to get values from database table to dictionary using LINQ. However I'm unable to understand the syntax. My requirement is the following:

    1) Call the method in  DAL from codebehind

    2) Get only ID and Name from database

    My code looks like the following (although this doesn't work):

    ASCX.CS

    Dictionary<int,string> peopleInformation = new Dictionary<int, string>();
    peopleInformation = myContext.GetAgeAndName(id);

    DAL:

    public Dictionary<int,string> GetAgeAndName(int personID)
    {
                Dictionary<int, string> people  = (from l in this.PeopleInfos
                                where l.ID == personID select l).ToDictionary<int,string>(l => l.ID, l => l.Name);

                return people;

    }

    How to proceed with this query, what is the correct syntax?


  • Re: Populate Dictionary from database using LINQ

    09-25-2009, 12:51 PM
    Answer
    • All-Star
      16,504 point All-Star
    • mendhak
    • Member since 05-28-2004, 6:58 PM
    • 51.507991,-0.127784
    • Posts 2,627

    I don't think you're doing this right.  Your method is called GetAgeAndName.  You are using L2S, and so you have entities you can use.  Can't you just do this?

    Calling page:

    PeopleInfos peopleInformation =  myContext.GetAgeAndName(id);
    TextBoxName.Text = peopleInformation.Name;
    TextBoxAge.Text = peopleInformation.Age;



    DAL:

    public PeopleInfos GetPersonById(int personID)
    {
     return (from l in this.PeopleInfos
                                where l.ID == personID select l).FirstOrDefault()

    }


    So, you're getting the object back and using its properties to do what you want.  The textboxes bit is just an example.  With the dictionary, you'd be duplicating data that's already there unnecessarily - you need to get the PersonInfo object from the database anyways, so might as well use the objects that L2S is providing you with. :)


    I bought a movie from the store the other day. It had a rating of 3.142 stars out of 5. Turns out it was a pi rated DVD.
Page 1 of 1 (2 items)