【问题标题】:Linq from list objects into one object with a list propertyLinq 从列表对象到一个具有列表属性的对象
【发布时间】: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 完全没有意义.. ?只是试验,试图掌握所产生的结果。
  • 真的那么不清楚吗?
  • 是的,请更清楚地解释您的问题。并告诉我们预期的结果。我正在努力理解您,但我仍然不明白您到底想要什么

标签: c# string linq list


【解决方案1】:

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

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

【讨论】:

  • 见鬼我怎么没想到.. !!好一个!!
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 2018-04-13
  • 2018-12-02
相关资源
最近更新 更多