我有一个AObject和一个BObject,定义如下
public class AObject {
public byte[] Types;
public string FirstProp;
public string SecondProp;
}
public class BObject {
public int Type;
public string FirstProp;
public string SecondProp;
}
现在我有一个我需要在BObject中复制的AObject列表但是AObject的Types属性应该在BObject List中分发;
它是列表值的简单示例:
AObjects= { new AObject(){ Types= 1010, first="first" ,second="second" }};
和BOject列表应包含以下行:
BObjects:
(1,“first”,“second”)
(0,“first”,“second”)
(1,“first”,“second”)
(0,“first”,“second”)
我想知道实现这个目标的最佳linq查询是什么?
答案 0 :(得分:1)
var BObjects = AObjects.SelectMany(a => a.Types.Select(t => new BObject
{
Type = t,
FirstProp = a.FirstProp,
SecondProp = a.SecondProp
}));
此处为AObject.Types
数组中的每个值创建BOject
的新实例。 FirstProp
和SecondProp
被{j}从AObject
复制而Type
填充了AObject.Types
的当前字节值。
答案 1 :(得分:1)
您可以使用Enumerable.SelectMany来解决问题。假设你有一个AObject
的数组
List<AObject> aObjects = new List<AObject>()
{
new AObject()
{
Types = new byte[] { 1, 0, 1, 0 },
FirstProp = "first1",
SecondProp = "second1" },
new AObject()
{
Types = new byte[] { 0, 1, 0, 1 },
FirstProp = "first2",
SecondProp = "second2"
},
//...
};
现在,您可以通过迭代每个BObject
的所有字节来生成可枚举的AObject
,如
IEnumerable<BObject> bObjects = aObjects.SelectMany(
a => a.Types.Select(
b => new BObject()
{
Type = b,
FirstProp = a.FirstProp,
SecondProp = a.SecondProp
}));
结果(在本例中)包含所需的8个项目:
{ 1, "first1", "second1" }
{ 0, "first1", "second1" }
{ 1, "first1", "second1" }
{ 0, "first1", "second1" }
{ 0, "first2", "second2" }
{ 1, "first2", "second2" }
{ 0, "first2", "second2" }
{ 1, "first2", "second2" }