score:4

Accepted answer

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;

}

score:5

daniel is nearly right, but an easy way to use the order of the incoming list is to order by the index of the id in that list:

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

note i don't know if that will work with a sql query, so this may be linq-to-objects only. it could also be very inefficient with large lists of ids.

score:7

edit: now that the mistake i made in understanding the requirement has been pointed out, i suggest this as a more performant method of achieving the desired result:

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

this won't do a search through the ids list for every element in db.mytypes (which is a good thing: it'll be fast!).

my original (incorrect) answer:

use an orderby clause.

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

it's not clear what type of object db.mytypes returns but, at a guess, the code could be simplified a little by avoiding the newing up of more mytype objects.

public list<mytype> getmytypes(list<int> ids) 
{ 
return (from mytype in db.mytypes 
        where ids.contains(mytype.id) 
        orderby mytype.id
        select mytype).tolist(); 
} 

Related Query

More Query from same tag