使用基于内部列表的.notation排序对象列表

时间:2011-03-15 20:19:42

标签: c# sorting linq-to-objects

我有这些课程:

[DataContract]
public class RowData
{
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public string AccountName { get; set; }
    [DataMember]
    public string AuthServerName { get; set; }
    [DataMember]
    public string SecurityName { get; set; }
    [DataMember]
    public string LastUser { get; set; }
    [DataMember]
    public string Status { get; set; }
    [DataMember]
    public string ClaimRelease { get; set; }
    [DataMember]
    public List<GameItem> Games { get; set; }
}

[DataContract]
public class GameItem
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Version { get; set; }
}

如果我知道自己在做什么,我会尽量猜测它应该是什么样的非工作查询。

public List<RowData> GetSortedByColumnList(Entities db, int ColumnID, string direction, int GameCount, List<RowData> rows)
{
...
    else if ((ColumnID > 3) && (ColumnID < GameCount + 4))
    {
        List<Game> gameslist = db.Games
            .Where(x => x.GameIsActive == 1)
            .ToList(); // Game has the key names

        int index = (ColumnID - GameCount) - 1; 

        // gamename is the name that i'd like to match for sorting purposes.
        string gamename = gameslist[index].GameName; 

        // *** LOOK HERE ****
        List<RowData> sortedList = rows
            .OrderBy(x => x.Games
                .Min(Games => Games.Version)
                .Where(Games => Games.Name == gamename))
            .ToList();

    rows = sortedList;
}

这是一个行的示例:

rows[0].id = 1
...
rows[0].Games[0].Name="A0"
rows[0].Games[0].Version=3
rows[0].Games[1].Name="B0"
rows[0].Games[1].Version=4

rows[1].id = 2
...
rows[1].Games[0].Name="A0"
rows[1].Games[0].Version=1
rows[0].Games[1].Name="B0"
rows[0].Games[1].Version=2

rows[2].id = 3
...
rows[2].Games[0].Name="A0"
rows[2].Games[0].Version=5

因此,如果字符串游戏名称将等于“B0”,我将根据版本号对列表进行排序,以便排序顺序为行[1],行[2],行[3]。注意行[2]中没有B0。

如何修改// *** LOOK HERE ****下的查询以按照我的意愿对列表进行排序?

  

编译错误1'char'不包含'Name'的定义,也没有扩展方法'Name'可以找到类型'char'的第一个参数(你是否缺少using指令或汇编引用?)

1 个答案:

答案 0 :(得分:2)

假设您正在寻找一个将按版本顺序返回具有特定名称的游戏列表的查询,您可能正在寻找类似于以下内容的内容:

List<GameItem> sortedList = rows
    .SelectMany(r => r.Games) // flattens to an ienumerable of games
    .Where(g => g.Name == gameName) // filters by the game name
    .OrderBy(g => g.Version) // orders by the game's version
    .ToList(); // converts the ienumerable to a list (of games).

如果您想要List<RowData>,我们可以假设每行只有一个特定名称的游戏,您可以执行以下操作:

// delegate for generating orderby key    
Func<RowData, string, int> sortKey = (r, gn) =>
{
    var game = r.Games.FirstOrDefault(g => g.Name == gn);
    return game != null ? game.Version : int.MaxValue; // or "zzzzz" if version is a string (something to put it to the end of the list)
};

List<RowData> result = rows
    .OrderBy(r => sortKey(r, gameName))
    .ToList();