DaveDev
DaveDev

Reputation: 42175

How to get List of results from list of ID values with LINQ to SQL?

I have a list of ID values:

List<int> MyIDs { get; set; }

I'd like to pass this list to an interface to my repository and have it return a List that match the ID values I pass in.

List<MyType> myTypes = new List<MyType>();

IMyRepository myRepos = new SqlMyRepository();

myTypes = myRepos.GetMyTypes(this.MyIDs);

Currently, GetMyTypes() behaves similarly to this:

public MyType GetMyTypes(int id)
{
    return (from myType in db.MyTypes
            where myType.Id == id
            select new MyType
            {
                MyValue = myType.MyValue
            }).FirstOrDefault();
}

where I iterate through MyIDs and pass each id in and add each result to a list.

How do I need to change the LINQ so that I can pass in the full list of MyIDs and get a list of MyTypes out? GetMyTypes() would have a signature similar to

public List<MyType> GetMyTypes(List<int> myIds)

Upvotes: 2

Views: 2603

Answers (2)

zerkms
zerkms

Reputation: 254896

public List<MyType> GetMyTypes(List<int> ids)
{
return (from myType in db.MyTypes
        where ids.Contains(myType.Id)
        select new MyType
        {
            MyValue = myType.MyValue
        }).ToList();
}

Upvotes: 2

Raj Kaimal
Raj Kaimal

Reputation: 8304

Untested

public List<MyType> GetMyTypes(List<int> myIds) {
  var x = from myType in db.MyTypes
          where myIds.contains(myType.Id)
          select new MyType {
            MyValue = mytype.Myvalue
          };
return x.ToList();
}

Upvotes: 1

Related Questions