假设我有这样的定义域类:使这一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";
}
}
}
是否有类似的东西,我可以做什么?
在此先感谢... !!!
http://codereview.stackexchange.com/ – 2012-03-15 21:22:54
你为什么更喜欢上一个版本?使用方法似乎是最合理和可读的 – BrokenGlass 2012-03-15 21:24:07
匿名方法中的“i”是什么? – 2012-03-15 21:34:34