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

问题描述

具有默认值的Linq查询.如果在数据库表中找不到该值,则应采用对象的默认值,然后在新行上将其添加到该表中.

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();

如何在DefaultIfEmpty中设置此默认值?

How to set this Default Values in DefaultIfEmpty???

新这就是我想作为一个查询进行的操作:

New 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();

推荐答案

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();

只要成员布局相同,此方法就可以使用.
这是可行的,因为匿名类型在运行时完全是匿名的...请阅读 MSDN条目有关此主题的更多信息:

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:

此外,我宁愿选择?? ...

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

这是一个工作小提琴

这篇关于使用DefaultIfEmpty和选择新{}的Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:18