Using DefaultIfEmpty with an object?

I saw an example on MSDN where it allowed you to specify a default value if nothing returned. See below:

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

Can this functionality be used 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 thought I could do something like this:

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

But they couldnโ€™t. It should be noted that I'm really trying to use this method for an object defined in my DBML using LINQ-To-SQL. Not sure if it matters in this case or not.

+4
source share
4 answers

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

 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"; } } 
+6
source

According to the MSDN page of this extension method, you can do what you want:

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

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

+2
source

I must admit that I'm not too sure that I understand your question, but I will try to suggest using a double question mark if the returned object can be null. For instance:

 myList.FirstOrDefault() ?? new myObject(); 
+1
source

You can create a default object. Like this:

 Object o_Obj_Default = new Object(); o_Obj_Default.id = 3; o_Obj_Default.name = "C"; 

And add it to the default value:

 string defaultName = objs.DefaultIfEmpty(o_Obj_Default).First().name; 

If your list of "objs" is empty, the result will be "C"

0
source

All Articles