How to order a list by ordering another list?

I have a method as follows. It returns a list MyTypes, which in order is ordered myType.Idby default. I would like this list to be ordered by the parameter idsthat I passed to the method.

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

So if idscontains

302
300
301

The returned list contains items in ascending order.

What do I need to do to return List<MyType>in order ids?

thank

edit: I tried orderby ids.IndexOf(myType.Id), but it throws an exceptionMethod 'Int32 IndexOf(Int32)' has no supported translation to SQL.

+3
source share
3 answers

The following worked:

public List<MyType> GetMyTypes(List<int> ids)
{
    var unordered = (from myType in db.MyTypes
                     where ids.Contains(myType.Id)
                     select new MyType
                     {
                         MyValue = myType.MyValue
                     }).ToList();

    var ordered = (from uo in unordered
                   orderby ids.IndexOf(uo.Id)
                   select uo).ToList();

    return ordered;

}
+4
source

EDIT: , , , :

    public static List<MyType> GetMyTypes(List<int> ids)
    {
        int index = 0;
        Dictionary<int, int> positions = ids.ToDictionary(c => c, c => index++);
        MyType[] results = new MyType[ids.Count];

        foreach (MyType aType in (from myType in db.MyTypes
                                  where ids.Contains(myType.Id)
                                  orderby myType.Id
                                  select myType))
        {
            results[positions[aType.Id]] = aType;
        }

        return results.ToList();
    }

db.MyTypes( : !).

() :

orderby.

public List<MyType> GetMyTypes(List<int> ids) 
{ 
return (from myType in db.MyTypes 
        where ids.Contains(myType.Id) 
        orderby myType.Id
        select new MyType 
        { 
            MyValue = myType.MyValue 
        }).ToList(); 
} 

, db.MyTypes , , , , MyType.

public List<MyType> GetMyTypes(List<int> ids) 
{ 
return (from myType in db.MyTypes 
        where ids.Contains(myType.Id) 
        orderby myType.Id
        select myType).ToList(); 
} 
+7

, - :

public List<MyType> GetMyTypes(List<int> ids)  
{  
    return (from myType in db.MyTypes  
        where ids.Contains(myType.Id)  
        orderby ids.IndexOf(myType.Id)
        select myType).ToList();  
}  

. , SQL-, Linq-to-objects. .

+5

Source: https://habr.com/ru/post/1743319/


All Articles