Search code examples
c#linqcontain

linqtosql maintain ordering of list


var convertedIds = ids.Select(id => Convert.ToInt32(id)).ToList();
return this.context.SupportedCharacterSets
    .Where(av => converteIds.Contains(av.id))
    .Select(av => new AsideItem 
                  { 
                     Id = av.id.ToString(CultureInfo.InvariantCulture), 
                     Name = av.name 
                  }).ToList();

convertedIds is a list of ints: { 2, 1 } - for example

When I am selecting from the db, it orders it 1,2 (which is expected), is there a way to not do this? I seen you can do a Dictionary object, however unsure if this is overkill?


Solution

  • You could use List.IndexOf in OrderBy:

    return this.context.SupportedCharacterSets
        .Where(av => converteIds.Contains(av.id))
        .AsEnumerable()  // to get  Linq-To-Objects
        .OrderBy(av => converteIds.IndexOf(av.id))
        .Select(av => new AsideItem 
        { 
           Id = av.id.ToString(CultureInfo.InvariantCulture), 
           Name = av.name 
        })
        .ToList();