[英]How to split object into list of objects by list property C#
I have an object which contains a property of type of List
of another objects: 我有一个对象,其中包含另一个对象的List
类型的属性:
public class MyObject {
public List<AnotherObject> MyProperty { get; set; }
}
MyProperty
has several items. MyProperty
有几个项目。
I want to split MyObject
into List<MyObject>
by MyProperty
items so that each MyObject contains MyProperty
with only one AnotherObject
as List<AnotherObject>
. 我想通过MyProperty
项目将MyObject
拆分为List<MyObject>
,以便每个MyObject包含MyProperty
其中只有一个AnotherObject
作为List<AnotherObject>
。
How to do it? 怎么做?
Use Enumerable.Select
to get an IEnumerable<MyObject>
: 使用Enumerable.Select
获得IEnumerable<MyObject>
:
var splits = existing.MyProperty.Select(ao => new MyObject {MyProperty = new List<AnotherObject> {ao}});
If you specifically need a List<MyObject>
: 如果您特别需要List<MyObject>
:
var asList = splits.ToList();
One way I can think of is to implement the IClonable interface into your MyObject
class. 我能想到的一种方法是在您的MyObject
类中实现IClonable接口。 This way you can make independent copies of the base object. 这样,您可以制作基础对象的独立副本。 All other properties in the class MyObject
will keep their values! MyObject
类中的所有其他属性将保留其值!
public class MyObject :ICloneable
{
public List<AnotherObject> MyProperty { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
Then iterate over the List<AnotherObject> MyProperty
create a copy and overwrite the List object in the copy: 然后遍历List<AnotherObject> MyProperty
创建一个副本并覆盖副本中的List对象:
Here is a working example: 这是一个工作示例:
MyObject mobj = new MyObject();
mobj.MyProperty = new List<UserQuery.AnotherObject>();
mobj.MyProperty.Add(new AnotherObject());
mobj.MyProperty.Add(new AnotherObject());
mobj.MyProperty.Add(new AnotherObject());
mobj.MyProperty.Add(new AnotherObject());
mobj.MyProperty.Add(new AnotherObject());
mobj.MyProperty.Add(new AnotherObject());
List<MyObject> splitList = new List<MyObject>();
for (int i = 0; i < mobj.MyProperty.Count; i++)
{
// get the reference to the object from the list
AnotherObject temp = mobj.MyProperty[i];
// make a deep copy of the base object
MyObject clone = mobj.Clone() as MyObject;
// overwrite the internal list and put the reference to the item into the list
clone.MyProperty = new List<AnotherObject> {temp};
// add the copied object to the split list
splitList.Add(clone);
}
Note that the AnotherObject
items are just references! 请注意, AnotherObject
项只是引用! so changing the values in the list of the base object will change the values in the single list items of the copies! 因此,更改基础对象列表中的值将更改副本的单个列表项中的值!
Using LINQ: 使用LINQ:
var query = from p in obj.MyProperty
select new MyObject() { MyProperty = new List<AnotherObject>() { p } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.