Linq to SQL: 自定义排序

某些时候我们需要按照某个特定的序列来完成结果排序,比如说按in条件中的Id顺序返回文章。
比如按此顺序排序:1,5,2,6,3,7,4,9

SQL语句如下:

select * from pdt_Music where MusicID in(1,2,3,4,5,6,7,8,9)
order by CHARINDEX(RTRIM(CAST(MusicID as NCHAR)),'5,2,8,1,3,4,6,7,9')

C#中LINQ语句如下:

public object AAA()
{
    List<Music> list = new List<Music>();
    var num = "1,4,3,2,5".Split(',').Select(v => Convert.ToInt32(v)).ToArray();
    var query = db_C56.Musics.Where(w => num.Contains(w.MusicID)).Select
        (mm => new
        {
            MusicID = mm.MusicID,
            MusicName = mm.MusicName,
            MusicUrl = mm.MusicUrl,
            CreateBy = mm.CreateBy,
            Status = mm.Status
        }).ToList();
    list = query.OrderBy(a => Array.IndexOf(num.Reverse().ToArray(), a.MusicID)).Select(s => new Music
    {
        MusicID = s.MusicID,
        MusicName = s.MusicName,
        MusicUrl = s.MusicUrl,
        CreateBy = s.CreateBy,
        Status = s.Status
    }).Skip(0).Take(10).ToList();
    return list;
}

public List<Music> BBB()
{
    List<Music> list = new List<Music>();
    var num = "1,2,3,4,5".Split(',').Select(v => Convert.ToInt32(v)).ToArray();
    var aa = (from m in db_C56.Musics
              where num.Contains(m.MusicID) && m.Status != "D"
              orderby m.MusicID
              select new
              {
                  m.MusicID,
                  m.MusicName,
                  m.MusicUrl,
                  CreateBy = m.CreateBy,
                  Status = m.Status
              }).ToList();
    list = aa.OrderBy(a => Array.IndexOf(num.Reverse().ToArray(), a.MusicID)).Select(s => new Music
    {
        MusicID = s.MusicID,
        MusicName = s.MusicName,
    }).Skip(0).Take(10).ToList();
    return list;
}



你可能感兴趣的:(Linq to SQL: 自定义排序)