Home > Blockchain >  Asp.Net Core : Get the list values ​of a table by list Id with Linq?
Asp.Net Core : Get the list values ​of a table by list Id with Linq?

Time:09-18

I have a color table that contains values, and I have a list of IDs that are the IDs of this table.I want to return only values ​​whose ID is in the list of IDs

Table Color: enter image description here

List Id :

{1,3,5}

I want to receive the values ​​whose IDs are 1, 3, and 5 as a list ?

CodePudding user response:

int[] ids = { 1, 3, 5 };

var result = ids
    .SelectMany(p => Colors.Where(r => r.Id == p)
    .Select(r => new { r.Name }))
    .ToList();

Or selecting the whole row:

var colors = ids
    .Select(p => Colors.Where(r => r.Id == p)
    .Select(r => r).FirstOrDefault())
    .ToList();

CodePudding user response:

List<string> result = Datatable.Rows
   .Cast<DataRow>()
   .Where(x => listOfId.Contains((int)x["Id"]))
   .Select(x => x["Name"])
   .ToList()

CodePudding user response:

With EF Core you have to use Contains:

int[] ids = { 1, 3, 5 };

var colors = db.Colors
    .Where(x => ids.Contains(x.Id))
    .ToList();

CodePudding user response:

Since you wrote Linq in the TAGs, I assume that you are using EntityFrameworkCore or LINQ to SQL or something similar.

In this case, this example will help you:

int[] ids = { 1, 2, 3 };

var nameList = db.Colors
    .Where(x => ids.Concat(x.Id))
    .Select(x => x.Name)
    .ToList();

where db is DbContext

  • Related