我搜索了很多类似的问题,但找不到解决这个问题的问题。很有可能我忽略了一些明显的东西,但请建议如何通过一次迭代来完成这项工作。
var dataWithResults =
from d in data
where d.QCResults != null
from q in d.QCResults
select new QCAMaterial
{
Name = q == null ? nodata : q.ComponentName,
Value = q == null ? nodata : q.Result
};
var dataWithNullResults =
from d in data
where d.QCResults == null
select new QCAMaterial
{
Name = nodata,
Value = nodata
};
答案 0 :(得分:0)
由于没有QCResults
以及QCResults
且其属性中没有特定数据的类都会获得nodata
值,因此您可以省略'其中'并将它们组合为:
IEnumerable<QCResult> dummycol = new[] {new QCResult()}; //assuming QCResult is the class exposed by the QCResults property
var res = from d in data
from q in d.QCResults ?? dummycol
select new QCAMaterial
{
Name = q == null ? nodata: q.ComponentName, //side note: can also be written as q?.ComponentName ?? nodata
Value = q == null ? nodata : q.Result
};
如果QCResults为空,则使用带有单个条目的虚拟集合。 虚拟集合也可以内联创建,但这应该更有效。
答案 1 :(得分:0)
您可以组合Enumerable.Empty
和Enumerable.DefaultIfEmpty
:
var allData =
from d in data
from q in d.QCResults ?? Enumerable.Empty<QCResult>().DefaultIfEmpty()
select new QCAMaterial
{
Name = q == null ? nodata : q.ComponentName,
Value = q == null ? nodata : q.Result
};
如果您想要将空列表(QCResults
)视为与null
列表相同,则可以修改查询:
var allData =
from d in data
from q in (d.QCResults ?? Enumerable.Empty<QCResult>()).DefaultIfEmpty()
select new QCAMaterial
{
Name = q == null ? nodata : q.ComponentName,
Value = q == null ? nodata : q.Result
};
答案 2 :(得分:0)
您可以使用SelectMany:
var result = data.SelectMany(d =>
{
return d.QCResults != null
? d.QCResults.Select(q => new QCAMaterial { Name = q.ComponentName, Value = q.Result})
: new List<QCAMaterial>{new QCAMaterial { Name = "no data", Value = "no data" }};
});