使这一LINQ投影查询更好
假设我有这样的定义域类:使这一LINQ投影查询更好
public class MyDomainItem
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
public string ItemStatus {get;set;}
public ClassA ObjectA {get;set;}
public ClassB ObjectB {get;set;}
}
然后,我有一个LINQ查询,看起来像这样:根据我所知道的
var mylist = from a in someList
join b in someOtherList on a.Id equals b.Id
select new MyDomainItem
{
PropertyA = a.SomeProperty,
PropertyB = b.SomeOtherProperty,
ObjectA = a,
ObjectB = b
}
,我可以解决ItemStatus
有两种方法:
foreach(var i in mylist)
{
if (i.ObjectA.YetAnotherProperty == "some criteria")
{
if (i.ObjectA.NestedObject.NestedProperty == "price is missing")
{
i.ItemStatus = "bad - category 1";
}
else
{
i.ItemStatus = "bad - category 2";
}
}
else
{
i.ItemStatus = "good";
}
}
或调用功能,在LINQ QUER解决y:
var mylist = from a in someList
join b in someOtherList on a.Id equals b.Id
select new MyDomainItem
{
PropertyA = a.SomeProperty,
PropertyB = b.SomeOtherProperty,
ObjectA = a,
ObjectB = b,
ItemStatus = ResolveStatus(a)
}
我脑海中有些东西只是不停地说,一定有更好的办法。我真的很喜欢做的事情大致是这样的:
var mylist = from a in someList
join b in someOtherList on a.Id equals b.Id
select new MyDomainItem
{
PropertyA = a.SomeProperty,
PropertyB = b.SomeOtherProperty,
ObjectA = a,
ObjectB = b,
ItemStatus =()=>
{
if (a.ObjectA.YetAnotherProperty == "some criteria")
{
if (a.ObjectA.NestedObject.NestedProperty ==
"price is missing")
{
return "bad - category 1";
}
else
{
return "bad - category 2";
}
}
else
{
return "good";
}
}
}
是否有类似的东西,我可以做什么?
在此先感谢... !!!
这样的事情呢?
select new MyDomainItem
{
PropertyA = a.SomeProperty,
PropertyB = b.SomeOtherProperty,
ObjectA = a,
ObjectB = b,
ItemStatus = (a.YetAnotherProperty == "some criteria")
? (a.NestedObject.NestedProperty == "price is missing"
? "bad - category 1"
: "bad - category 2")
: "good";
虽然我会建议扩展ObjectA与属性,为您做这个评估,它在LINQ查询看起来不太好。如果你没有来源,你可以使用一个扩展方法
string GetItemStatus(this ObjectA item) {
if (item.YetAnotherProperty != "some criteria") {
return "good";
}
if (item.NestedObject.NestedProperty == "price is missing") {
return "bad - category 1";
}
return "bad - category 2";
}
关于三元运算符的好主意,它离我想要的更近了一步...... – code4life 2012-03-16 14:27:46
你为什么不只是创建一个接受两个属性和两个对象,并设置状态MyDomainItem构造?它将使MyDomainItem成为一个更健壮的类(状态有效性不会取决于调用者的良好意愿),并且还将解决您的样式问题。
是的,使用MyDomainItem(a,b)和MyDomainItem.Resolve() – Ray 2012-03-15 21:41:43
http://codereview.stackexchange.com/ – 2012-03-15 21:22:54
你为什么更喜欢上一个版本?使用方法似乎是最合理和可读的 – BrokenGlass 2012-03-15 21:24:07
匿名方法中的“i”是什么? – 2012-03-15 21:34:34