Linq with DefaultIfEmpty with select new {}

3m1n4 picture 3m1n4 · Aug 14, 2014 · Viewed 9.2k times · Source

Linq query with default values. If in DB Table this values are not found, than default values from object should be taken, and later on new row will be added to this table.

It should go like this, but this does not work:

var name_country = (from m in ctx.person
                where (m.name == oPerson.name || m.country == oPerson.country)
                 select new 
                 {
                   m.name, m.country
                 }
                ).DefaultIfEmpty
                               (
                                 oPerson.name,
                                 oPerson.country
                               ).FirstOrDefault();

How to set this Default Values in DefaultIfEmpty???

New Edit: This is what I want to make as one query:

string name = (from m in ctx.person
                where (m.name == oPerson.name || m.country == oPerson.country)
                 select  
                   m.name
                ).DefaultIfEmpty
                               (
                                 oPerson.name,
                               ).FirstOrDefault();
string country = (from m in ctx.person
                where (m.name == oPerson.name || m.country == oPerson.country)
                 select 

                  m.country

                ).DefaultIfEmpty
                               (
                                 oPerson.country
                               ).FirstOrDefault();

Answer

user57508 picture user57508 · Aug 14, 2014
var name_country = (from m in ctx.person
            where (m.name == oPerson.name || m.country == oPerson.country)
             select new 
             {
               m.name, m.country
             }
            ).DefaultIfEmpty
                           (new {
                             oPerson.name,
                             oPerson.country
                           }).First();

This will work as long as the member-layout is identical.
This works, as anonymous types are anonymous at run-time at all ... Please read the MSDN-entry for more information on this topic:

If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.

besides I would rather go for a ?? ...

var name_country = (from m in ctx.person
                    where (m.name == oPerson.name || m.country == oPerson.country)
                    select new 
                    {
                        m.name,
                        m.country
                    }).FirstOrDefault() ?? new {
                        oPerson.name,
                        oPerson.country
                    };

edit: here's a working fiddle