本文介绍了使用DefaultIfEmpty与对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到MSDN上的一个例子,它会让你指定默认值,如果什么都不会返回。请看下图:

I saw an example on MSDN where it would let you specify the default value if nothing is returned. See below:

List<int> months = new List<int> { };
int firstMonth2 = months.DefaultIfEmpty(1).First();

是否可以使用此功能与对象?例如:

Is it possible to use this functionality with an object? Example:

class object
{
  int id;
  string name;
}

code:

code:

List<myObjec> objs = new List<myObjec> {};
string defaultName = objs.DefaultIfEmpty(/*something to define object in here*/).name;

更新:

我想我可以做这样的事情:

I was thinking I could do something like this:

List<myObjec> objs = new List<myObjec> {};
string defaultName = objs.DefaultIfEmpty(new myObjec(-1,"test")).name;

但一直没能。应当指出的是,我实际上试图在使用LINQ到SQL我DBML定义的对象上使用此方法。不知道如果这是在这种情况下,或没有区别。

But haven't been able to. It should be noted that I am actually trying to use this method on an object defined in my DBML using LINQ-To-SQL. Not sure if that makes a difference in this case or not.

推荐答案

您需要传递一个实例化类作为一个参数 DefaultIfEmpty

You need to pass an instantiated class as a parameter of the DefaultIfEmpty.

class Program
{
    static void Main(string[] args)
    {
        var lTest = new List<Test>();
        var s = lTest.DefaultIfEmpty(new Test() { i = 1, name = "testing" }).First().name;
        Console.WriteLine(s);
        Console.ReadLine();

    }
}

public class Test
{
    public int i { get; set; }
    public string name { get; set; }
}

要添加到它,并使其更加优雅一点(IMO)中添加一个默认的构造函数:

To add to it and make it a bit more elegant (IMO) add a default constructor:

class Program
{
    static void Main(string[] args)
    {
        var lTest = new List<Test>();
        var s = lTest.DefaultIfEmpty(new Test()).First().name;
        Console.WriteLine(s);
        Console.ReadLine();

    }
}

public class Test
{
    public int i { get; set; }
    public string name { get; set; }

    public Test() { i = 2; name = "testing2"; }
}

这篇关于使用DefaultIfEmpty与对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:25