Linq从列表对象到一个具有list属性的对象

时间:2014-03-08 23:07:39

标签: c# string linq list

我尝试使用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有一个列表,其中包含一个颜色等于一个元素的元素。

1 个答案:

答案 0 :(得分:1)

您只需将您尝试过的第一个查询放入第二个,如下所示:

 destinationObject = MyObjectList.Select(x =>
        new ObjectToSelectInto()
        {
           AllProductColors = MyObjectList.Select(y => y.ProductName).ToList(),
           ImgUrl = x.ImgUrl,
           ProductName = x.ProductName
       }).First();
相关问题