Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DefaultIfEmpty with an object?

Tags:

c#

.net

linq

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:

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

UPDATE:

I was thinking I could do something like this:

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

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.

like image 921
Abe Miessler Avatar asked Nov 01 '10 20:11

Abe Miessler


3 Answers

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; }
}

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"; }
}
like image 95
Dustin Laine Avatar answered Oct 13 '22 04:10

Dustin Laine


As per the MSDN page on this Extension Method you can do what you want:

http://msdn.microsoft.com/en-us/library/bb355419.aspx

Check the sample on this page for an example on how to use this with an object.

like image 2
Waleed Al-Balooshi Avatar answered Oct 13 '22 05:10

Waleed Al-Balooshi


i must admit i am not too sure i understand your question, but i'll try to suggest using double question mark if the returned object might be null. Like so:

myList.FirstOrDefault() ?? new myObject();
like image 1
Peter Perháč Avatar answered Oct 13 '22 05:10

Peter Perháč