[英]Linq with DefaultIfEmpty with select new {}
Linq查询具有默认值。 如果在DB Table中找不到此值,则应该从object获取默认值,稍后将在此表中添加新行。
它应该是这样的,但这不起作用:
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中设置此默认值???
新编辑:这是我想要作为一个查询:
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条目以获取有关此主题的更多信息:
如果程序集中的两个或多个匿名对象初始值设定项指定了具有相同顺序且具有相同名称和类型的属性序列,则编译器会将对象视为相同类型的实例。 它们共享相同的编译器生成的类型信息。
除了我宁愿去找??
...
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
这个重载
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
this IEnumerable<TSource> source,
TSource defaultValue
)
您应该创建一个新的匿名对象 ,设置它的属性,并将其传递给构造函数。
假设你有一个看起来像的Person
类
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
你想在这里做的是创建一个Person
的新实例(如果没有从你的数据库查询返回一个,它会自动设置每个特定属性类型的默认值),例如
var name_country = (from m in ctx.person
where (m.name == oPerson.name || m.country == oPerson.country)
select new Person
{
Name = m.name,
Country = m.country
}).FirstOrDefault() ?? new { oPerson.name, oPerson.country };
刚刚意识到你要默认oPerson
实例中的字段而不是新实例。 因此,假设oPerson
也是一个具有完全相同成员结构的匿名对象,您可以这样做
var name_country = (from m in ctx.person
where (m.name == oPerson.name || m.country == oPerson.country)
select new
{
m.name,
m.country
})
.DefaultIfEmpty(aPerson)
.FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.