Patrick Fritch
Patrick Fritch

Reputation: 199

Selecting multiple from LINQ query

I use this little piece of code to get the IDs I need, and put them in an array

var userids = from a in db.Person
              select a.idlist;

string[] idarray = userids.FirstOrDefault().ToString().Split(';');

How can I use this array of ids to select the matching rows in another query like this

[HttpGet]
public ActionResult GetStuff()
{
    var Item = from a in db.Table
               where a.id == idarray[0]
               and where a.id == idarray[1]
               and where a.id == idarray[2]
               etc...
               select new
                   {
                       a.itemid,
                       a.Element
                   };

    return Json(Item, JsonRequestBehavior.AllowGet);
}

Upvotes: 1

Views: 1989

Answers (4)

Taylor Jones
Taylor Jones

Reputation: 400

Here's what I usually do.

Get the IDs you need:

var ids = something.Where(s => s.SomeCondition).Select(s => s.Id);

Now Lets get the data based on the Ids:

var response = anothertable.Where(a => ids.Contains(a.Id);

You then can make it a list, array, or whatever you want to do with it. It will go through all the records in anothertable and find the records where the a.Id matches any of the ids.

Upvotes: 0

teo van kot
teo van kot

Reputation: 12491

Don't you want to use Extension Method Lambda syntax? I is same Linq, but just has more code-like view:

var Item = db.Table.Where(x => x.Contains(a.id))
           .Select(x => new
               {
                   a.itemid,
                   a.Element
               }).ToArray();

Upvotes: 0

Shahzad Khan
Shahzad Khan

Reputation: 530

var Item = from a in db.Table
           where idarray.Contains(a.id)
           select new
               {
                   a.itemid,
                   a.Element
               }.ToArray();

Upvotes: 0

Gardax
Gardax

Reputation: 370

Try something like this:

var Item = from a in db.Table
           where idarray.Contains(a.id)
           select new
               {
                   a.itemid,
                   a.Element
               };

Upvotes: 1

Related Questions