【发布时间】:2014-03-08 23:07:38
【问题描述】:
我正在尝试使用 Linq 从 MyObject 列表中选择属性 ProductColor 到属性 AllProductColors
public class MyObject
{
public string ImgUrl { get; set; }
public string ProductName { get; set; }
public string ProductColor { get; set; }
}
public class ObjectToSelectInto
{
public string ImgUrl { get; set; }
public string ProductName { get; set; }
public List<string> AllProductColors { get; set; }
}
//*** CREATING EXAMPLE ***///
List<MyObject> MyObjectList = new List<MyObject>();
ObjectToSelectInto destinationObject = new ObjectToSelectInto();
//I can do it like this, but then I
// would have to do this for every list item, not good!
destinationObject.AllProductColors =
MyObjectList.Select(x => x.ProductColor).toList();
//*** This fails ***///
destinationObject = MyObjectList.Select( x =>
new destinationObject {
AllProductColors = x.ProductColor.ToList(),
ImgUrl = x.ImgUrl.First().toString(),
ProductName = x.ProductName .First().toString()
}
我希望它是这样的。
destinationObject 有一个元素列表,其中一种颜色等于一个元素。
【问题讨论】:
-
不太明白您在尝试什么,但听起来 SelectMany 可能是正确的调用方式?
-
这有什么意义?
x.MaterialColor.ToCharArray(0,x.MaterialColor.Length)你的字符串已经是一个字符数组了? -
@Selman22 完全没有意义.. ?只是试验,试图掌握所产生的结果。
-
真的那么不清楚吗?
-
是的,请更清楚地解释您的问题。并告诉我们预期的结果。我正在努力理解您,但我仍然不明白您到底想要什么