【发布时间】:2016-12-29 20:31:27
【问题描述】:
我正在研究一些 LINQ 排序,因为我有一个 Id 列表,我需要按顺序对它们进行排序。但是,某些 id 需要优先于标准排序。
鉴于此 C# 代码(可以粘贴到 .NET Fiddle 中进行测试),排序按我的需要工作,但我不明白为什么 contains 上的 not (!) 运算符给了我顺序正确吗?
我的预期排序输出是 (5, 1, 2, 3, 4, 6, 7, 8, 9)。
如果我的订单中有Contains,它不应该为返回true 的行提供排序优先级吗?相反,它似乎为返回 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;}
}
}
为什么会发生这种情况的解释是什么?
【问题讨论】:
标签: c# .net linq sorting operators