I have an array of string that needs to be search on a context.
List<string> nameList
and I have a context to be searched on
context.Name
I have my code here:
List<Guid> nameIds= context.Name
.Where(n => nameList.Contains(n.Description)
.Select(n=> n.NameId)
.ToList();
I can get the ID of my names, but I want it to be ordered by the nameList
, not by the context itself.
For example. The names on my database are [Ben, Maria, Liza] with [0, 1, 2] id respectively. And my nameList
is [Liza, Maria] orderly. The nameIds
will be [1,2] because it is ordered by the context. I want it to be ordered by nameList
; [2,1]
You can do the ordering based on items order of nameList
by Linq Join
and OrderBy
operation. The below statements result have the NameId
collection based on the items order of nameList
.
List<Guid> nameIds = context.Name.Where(n => nameList.Contains(n.Description)).ToList()
.Join(nameList, n => n.Description, l => l, (n, l) => new {n.NameId, l})
.OrderBy(o => o.l)
.Select(s => s.NameId).ToList();
If you notice in above above :
Where with Contains
query intact to make sure that only filtered data is returned from Database. If you remove this clause and do the direct join, that full set of data will be returned from DB which can cause the performance issue in your application.IQueryable
,ToList
execute the query to fetch the data from databaseJoin
operation joins the DB data and nameList
OrderBy
orders the data based on description (actual order of nameList
items)Select
selects the NameIdCreated this dotnetfiddle to demo how the whole linq statement works.
You want the result keeping the search data order.
So no order by, just join them should work for you.
Here is an example for you
class Program
{
static void Main(string[] args)
{
// searched data from db
List<Person> people = new List<Person> { new Person(0, "Ben"), new Person(1, "Maria"), new Person(2, "Liza") };
// search data
List<string> nameList = new List<string> { "Liza", "Maria" };
var result = nameList.Join(people, n => n, p => p.Name, (n, p) => p.Id).ToList();
}
}
class Person
{
public Person(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; set; }
public string Name { get; set; }
}