gpt4 book ai didi

c# - 排序后变量为空

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:57 25 4
gpt4 key购买 nike

我从 List<T> 继承了一个自定义类但是在排序之后我的变量变成了NULL

public class Test
{
public int No { get; set; }
}

public class TestList : List<Test>
{

}

class Program
{
static void Main(string[] args)
{
TestList tests = new TestList() {
new Test(){ No = 101 },
new Test(){ No = 201 },
new Test(){ No = 300 },
new Test(){ No = 401 },
new Test(){ No = 500 },
new Test(){ No = 601 }
};
tests = tests.OrderBy(o => o.No).ToList() as TestList;

}

}

谁能告诉我为什么 TestList 会变为 null 以及如何在此列表上排序?

最佳答案

tests.OrderBy(o => o.No).ToList()返回 List<Test> . List<Test>无法转换为 TestList - 由于继承,它应该是显而易见的。当无法转换时,运算符 as返回 null (你的情况)。

您可以执行以下操作:

public class TestList : List<Test>
{
public TestList ()
{
}

public TestList (IEnumerable<Test> items)
: base(items)
{
}
}

tests = new TestList(tests.OrderBy(o => o.No));

但最好使用Sort (不需要 LINQ)。

tests.Sort(delegate(Test x, Test y)
{
return x.No.CompareTo(y.No);
});

或者更简单:

tests.Sort((Test x, Test y) => x.No.CompareTo(y.No));

Reference

关于c# - 排序后变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com