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

I have a list of ID values:

List<int> MyIDs { get; set; }

      

I would like to pass this list to the frontend in my repository and return it a list that matches the id values ​​I pass.

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 MyID and pass each id and add each result to the list.

How do I change LINQ so that I can go to the full list of MyIDs and get the list of MyTypes? GetMyTypes () will have a signature similar to

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

      

+2


a source to share


2 answers


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

      



+1


a source


Not verified



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

      

+1


a source







All Articles