繁体   English   中英

SingleOrDefault:在Custome结构上不返回null

[英]SingleOrDefault : Not return null on Custome structure

我有结构,

public struct Test
{
    public int int1;
    public string str;
}

在我的代码中,我有,

List<Test> list = new List<Test>()
{ 
    new Test(){ int1 =1, str="abc" }, 
    new Test(){ int1 =2, str="abc" }
};

当我尝试在List<Test> list上使用SingleOrDefault时,搜索条件int1的值等于3

Test result = list.SingleOrDefault(o => o.int1 == 3);

这里的结果具有默认值,表示int1 = 0和str = null。 如果不满足搜索条件,我想要null值。 有人指着我怎么做到这一点?

您将不会返回null,因为Test是一个结构,一个值类型。 Test更改为类,它将返回null。

值类型不可为空,因此您要么必须使用类,要么可以使用可空的Test?

但是如果你想坚持使用struct ,你应该创建一个名为Empty的静态字段来检查空值:

public struct Test
{
    public static readonly Test Emtpy = new Test();
    public int int1;
    public string str;

    public static bool operator ==(Test a, Test b)
    {
        return a.int1 == b.int1 && Equals(a.str, b.str);
    }

    public static bool operator !=(Test a, Test b)
    {
        return !(a==b);
    }
}

这是一个通过.Net框架找到的约定。 如果您以后想要检查null (您可能会做什么),请检查Test.Empty

List<Test> list = new List<Test>(){ new Test(){ int1 =1,str="abc"}, new Test(){ int1 =2,str="abc"}};
Test result = list.SingleOrDefault(o => o.int1 == 3);

if (result != Test.Emtpy)
    ...

一个脏修复:

    Test result = list.FirstOrDefault(o => o.int1 == 3);

    if (result.Equals(default(Test)))
    {
        // not found
    }
    else
    {
        // normal work
    }

只有在您确定原始列表永远不包含默认结构时才使用此选项(new Test(){int1 = 0,str = null})

Test? result = list.Select(o => (?Test)o).SingleOrDefault(o => o.Value.int1 == 3);

它不漂亮,但它确实起作用。 您可能希望将该模式提取到辅助方法中。

暂无
暂无

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

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