How to search a context using a list of string and order it?

.net c# entity-framework entity-framework-core


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


I have my code here:

            List<Guid> nameIds= context.Name
                .Where(n => nameList.Contains(n.Description)
                .Select(n=> n.NameId)

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]

10/13/2019 5:53:03 PM

Accepted Answer

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 :

  • I left the 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.
  • On returned IQueryable,ToList execute the query to fetch the data from database
  • Join operation joins the DB data and nameList
  • OrderBy orders the data based on description (actual order of nameList items)
  • Select selects the NameId

Created this dotnetfiddle to demo how the whole linq statement works.

10/14/2019 5:59:45 AM

Popular Answer

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

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow