C#LINQ Orderby-正确/错误如何影响orderby? [英] C# LINQ Orderby - How does true/false affect orderby?

查看:220
本文介绍了C#LINQ Orderby-正确/错误如何影响orderby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究LINQ排序,因为我有一个ID列表,因此需要按顺序对其进行排序.但是,某些ID需要优先于标准顺序.

I was studying a bit of LINQ ordering as I have a list of Ids, and I need to order them sequentially. However, there are certain ids that need to take precedence over the standard ordering.

给出此C#代码(可以将其粘贴到 .NET Fiddle 进行测试),按我的要求可以进行排序,但是我不明白为什么包含上的not(!)运算符会给我正确的排序?

Given this C# code (which can be pasted into .NET Fiddle to test) the ordering works as I need it to, but I don't understand why a not (!) operator on a contains is giving me the correct ordering?

我期望的订购输出为(5, 1, 2, 3, 4, 6, 7, 8, 9).

My expected ordering output is (5, 1, 2, 3, 4, 6, 7, 8, 9).

如果我有 Contains 在我的排序中,它不应该为返回true的行赋予排序优先级吗?相反,它似乎为返回false的行赋予了排序优先级.

If I have a Contains in my ordering, shouldn't it give ordering priority to the rows that returned true? Instead it appears to give ordering priority to rows that return false.

using System.Linq;
using System;

public class Program
{
  public static void Main()
  {
    var numbersToFilterBy = new [] {5, 11, 20};

    var x = new [] {new XClass(){Id = 1}, new XClass(){Id = 9}, new XClass(){Id = 5}, new XClass(){Id = 3}, new XClass(){Id = 4}, new XClass(){Id = 2}, new XClass(){Id = 6}, new XClass(){Id = 8}, new XClass(){Id = 7}};

    var trueData = (from data in x
                   orderby !numbersToFilterBy.Contains(data.Id), data.Id
                    select data).ToList();

    foreach(var item in trueData){
        Console.WriteLine(item.Id);
  }
}

public class XClass{
    public int Id{get;set;}
  }
}

为什么会发生这种情况?

What is the explanation as to why this happens?

推荐答案

OrderBy 方法将按默认升序对项目进行排序.现在,假设布尔值的数字表示为:

The OrderBy method will sort items in ascending order by default. Now, given that the numeric representation of a boolean is:

  • false = 0
  • true = 1
  • false = 0
  • true = 1

false值自然会排在第一位.如果要颠倒顺序,只需使用descending关键字:

false values will naturally come first. If you want to reverse the order just use the descending keyword:

var trueData = (from data in x
               orderby numbersToFilterBy.Contains(data.Id) descending, data.Id
                select data).ToList();

这篇关于C#LINQ Orderby-正确/错误如何影响orderby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆