简体   繁体   English

SingleOrDefault:在Custome结构上不返回null

[英]SingleOrDefault : Not return null on Custome structure

I have structure, 我有结构,

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

and in my code I have, 在我的代码中,我有,

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

When I am trying to use SingleOrDefault on List<Test> list with search criteria int1 value equals 3 当我尝试在List<Test> list上使用SingleOrDefault时,搜索条件int1的值等于3

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

Here result have value with default values, means int1 = 0 and str = null. 这里的结果具有默认值,表示int1 = 0和str = null。 Here I want null value if search criteria not satisfied. 如果不满足搜索条件,我想要null值。 Anyone point me How I can do this? 有人指着我怎么做到这一点?

You will not get null returned because Test is a struct, a value type. 您将不会返回null,因为Test是一个结构,一个值类型。 Change Test to a class and it will return null. Test更改为类,它将返回null。

Value types are not nullable, so you either have to use a class, or a nullable Test? 值类型不可为空,因此您要么必须使用类,要么可以使用可空的Test? .

But if you want to stick with a struct , you should create a static field called Empty to check for empty values: 但是如果你想坚持使用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);
    }
}

It's a convention that you will find across the .Net framework. 这是一个通过.Net框架找到的约定。 If you later want to check for null (what you probably do), check for Test.Empty instead. 如果您以后想要检查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)
    ...

A dirty fix: 一个脏修复:

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

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

Use this only if you pretty sure that your original list never contains the default struct ( new Test() { int1 = 0, str = null } ) 只有在您确定原始列表永远不包含默认结构时才使用此选项(new Test(){int1 = 0,str = null})

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

It is not pretty, but it does its job. 它不漂亮,但它确实起作用。 You might want to extract that pattern into a helper method. 您可能希望将该模式提取到辅助方法中。

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

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