C# LINQ - 将行拆分为两行

3
抱歉可能问了个愚蠢的问题,但我有这个 Ienumerable<> 集合。

Dataset

我需要将名称和百分比分别拆分成不同的行,并为这些行复制ProductId和RowIndex(我知道这样做效率不高,但这就是需要完成的任务)。可能还需要一个新字段来指定组合行包含哪些数据。
例如,
ProductId, Name , Percent, RowIndex 2301283 , PLACEHOLDER, 12.20 , 1
应该变成这样:
ProductId, DataType, Value , RowIndex 2301283 , Name , PLACEHOLDER, 1 2301283 , Percent , 12.20 , 1 等等等等
此外,它们不能嵌套在其他列表或可枚举对象中。如果有意义的话,是否可以在LINQ中实现?

你需要单个结果序列还是必须有两个序列:第一个序列包含名称,第二个序列包含百分比?如果是单个序列,请描述您要包含数据的数据类型。 - Dennis
.Select(entireRow => Tuple.Create(entireRow.Left, entireRow.Right).UnZip(); - Zazaeil
@SeM 要让 LINQ 数据显示在上面的表格中,仅这一步就需要很长时间... - impo
4个回答

1
据我所见,您想将每个GI对象转换为2个新对象,并将所有这些成对对象展平为一个可枚举对象。希望我理解您的意思是正确的。
我认为SelectMany可以完成这项工作。
yourEnumerable.SelectMany(x => new[] {
    new { ProductId = x.ProductId, DataType = "Name", Value = x.Name, RowIndex = x.RowIndex },
    new { ProductId = x.ProductId, DataType = "Percent", Value = x.Percent, RowIndex = x.RowIndex }
})

这似乎解决了问题,非常感谢!这个问题困扰我几个小时了! - impo

1
你可以使用LINQ的.Select方法和一个新的类来实现。为了高效地完成这个任务,你可以使用Tuple<T1, T2>结构:
public class AttributeData
{
    public int ProductId { get; set; }
    public string DataType { get; set; }
    public string Value { get; set; }
    public int RowIndex { get; set; }
}

yourEnumerable.Select(x => 
     Tuple.Create(
         new AttributeData
         { 
            ProductId = x.ProductId,
            DataType = "Name",
            Value= x.Name,
            RowIndex= x.RowIndex
         },
         new AttributeData
         { 
            ProductId = x.ProductId,
            DataType = "Percent",
            Value= x.Percent,
            RowIndex= x.RowIndex
         }
      ).ToList();

1
//list is your data collection
//newlist is the result
var newlist = new List<dynamic>();
list.ForEach(w =>
{
    newlist.Add(
        new {w.ProductID,DataType="Percent",Value=w.Percent,w.RowIndex}
    );
    newlist.Add(
        new {w.ProductID,DataType="Name",Value=w.Name,w.RowIndex}
    );
});
newlist.Dump();

希望它能帮到你 :-)

你在这里枚举列表两次。由于.Select实际上是一个函数对象,select(g).select(f)将始终等于select(g . f),后者的完成操作速度最多快两倍(在最坏情况下)。 - Zazaeil
1
EmrahSüngü Süngü,Sereja Bogolubov感谢你们,我已经修复了。 - Wei Lin

0
尝试像这样使用:
这将直接返回结果为 SelectMany
   var data = (from entity in Entities
    select new [] {
         new { entity.ProductId, DataType = "Name", Value= entity.Name, entity.RowIndex},
         new { entity.ProductId, DataType = "Percentage", Value= entity.Percentage, entity.RowIndex},
    }).SelectMany(e=> e);

或者

这将给你一个列表,其中每个元素都包含名称和百分比行。

   var data = (from entity in Entities
    select  new {
         NameEntity = new { entity.ProductId, DataType = "Name", Value= entity.Name, entity.RowIndex},
         PercentageEntity = new { entity.ProductId, DataType = "Percentage", Value= entity.Percentage, entity.RowIndex},
    });

  foreach(var d in data) {
    //d.NameEntity
    //d.PercentageEntity  
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接