简体   繁体   English

我可以在IOrderedEnumerable列表中添加where子句吗?

[英]Can I add a where clause to an IOrderedEnumerable list?

I have a list of arrays. 我有一个数组列表。 Each array consists of a score and a difficulty. 每个数组包括一个分数和一个难度。 Read in from a text file. 从文本文件读入。

This is how I get the data and order it by the score in descending order. 这就是我获取数据并按分数降序对其进行排序的方式。

// load highscores
public void LoadScores()
{
    // loop through each line in the file
    while ((line = file.ReadLine()) != null)
    {
        // seperate the score from the difficulty
        lineData = line.Split(',');

        // add each line to the list
        list.Add(lineData);
    }

    // order the list by descending order
    IOrderedEnumerable<String[]> scoresDesc = list.OrderByDescending(ld => lineData[0]);

}

Is it possible to add the a clause to the IOrderedEnumerable so that it orders by the score in descending order where the difficulty is 1 ? 是否可以在IOrderedEnumerable添加a子句,使其以难度为1降序按分数排序?

Assuming the "difficulty" is the second item in the array: 假设“难度”是数组中的第二项:

 IEnumerable<String[]> scoresDesc =
     list.OrderByDescending(ld => lineData[0])
         .Where(ld => lineData[1] == 1);

You can sort it afterwards, but Where returns an IEnumerable<T> , not an IOrderedEnumerable<T> , so if you need it to be an IOrderedEnumerable<T> then it's cleaner (and faster) to filter the list first: 可以对其进行排序,但是Where返回IEnumerable<T> ,而不是IOrderedEnumerable<T> ,因此,如果您需要将其作为IOrderedEnumerable<T>那么使用它更干净(并且更快)来首先过滤列表:

 IOrderedEnumerable<String[]> scoresDesc =
     list.Where(ld => lineData[1] == 1)
         .OrderByDescending(ld => lineData[0]);

(this is where var eases some pain, since you aren't bound to the return type) (这是var减轻一些痛苦的地方,因为您没有绑定到返回类型)

如果要针对困难1进行过滤,则可以使用.Where()扩展方法,如果要按多个字段进行排序,则可以使用.ThenBy()扩展方法。

首先过滤,然后订购:

list.Where(x => x.difficulty == 1).OrderByDescending(ld => lineData[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM