This seems fairly easy but I can t focus.
Let s say I have got 2 classes defined like this:
class Class1
{
public int Document;
public decimal Amount;
}
class Class2
{
public string Document;
public decimal Amount;
}
有 IEnumberable<Class1> 结果1
和 >IEnumberable<Class2> 结果2
定义并填满了数据。
我有一个三等的 定义像这样:
class ResultClass
{
public string Document;
public decimal? AmountFromClass1;
public decimal? AmountFromClass2;
}
I want a LINQ query which selects some fields from the first result and some fields from the second result and puts them in a third result defined as List<ResultClass> result
.
For example, if I have the first result (result1
) populated like this:
Document Amount
1 1.55
2 2.55
和第二个结果 ( 结果2
), 人口组成像这样 :
Document Amount
"d-1" 1.22
"d-2" 2.22
我希望最终的 结果
包含类似的东西( 顺序不重要) :
Document AmountFromClass1 AmountFromClass2
"1" 1.55 null
"d-1" null 1.22
"2" 2.55 null
"d-2" null 2.22
目前我使用两个 < code> foreach 语句来做此操作, 例如 :
List<ResultClass> result = new List<ResultClass>();
foreach (var o in result1)
result.Add(new ResultClass
{
Document = o.Document.ToString(),
AmountFromClass1 = o.Amount,
AmountFromClass2 = null
});
foreach (var o in result2)
result.Add(new ResultClass
{
Document = o.Document,
AmountFromClass1 = null,
AmountFromClass2 = o.Amount
});
But I would like to do this using LINQ.
Is it possible?
EDIT: TO REFINE THE QUESTION (also added the entity-framework tag)
As this is just a code example, I am aware that there might be no real benefits of doing this in a single LINQ statement as it would do the same.
However, I am looking for a performance improvement where result1
and result2
are actually IQueryables from LINQ-to-Entities, in a way so I could do something like this:
List<ResultClass> MyFunc()
{
Database DB = new Database(); // object context
var result1 = DB.Class1s.Where(...);
var result2 = DB.Class2s.Where(...);
return SomeMagic()
.Select(x => new ResultFunc { ... })
.ToList();
}