LINQ:从lst中选择distinct,并将不同的属性附加到一个属性中



我有以下问题,我想寻求帮助。我必须选择不同的值(一个属性的标准(,然后从其他属性中提取不同的值。

假设我有以下类,其中每个BOM都有一个或多个具有不同PartsQtyPerFlatComponents

示例:

public sealed class BOM {
    public string FlatComponent {
        get;
        set;
    }
    public string Part {
        get;
        set;
    }
    public string QtyPer {
        get;
        set;
    }
    public BOM(String flatComponent, String part, String qtyPer) {
        this.FlatComponent=flatComponent;
        this.Part=part;
        this.QtyPer=qtyPer;
    }
}

List<BOM> list=new List<BOM>();
list.Add(new BOM("a", "1", "2"));
list.Add(new BOM("a", "3", "4"));
list.Add(new BOM("b", "5", "6"));
list.Add(new BOM("c", "7", "8"));
list.Add(new BOM("c", "9", "0"));

如何使用LINQ(用逗号分隔(在每个属性中选择不同的FlatComponents及其不同的值?

结果=[["a","1,3","2,4"],["b","5","6"],["c","7,9","8,0"]]

我试过使用.Distinct(),但我对LINQ还很陌生。。。

试试这个:

var result = list
    .GroupBy(e => e.FlatComponent)
    .Select(e => new BOM
        {
            FlatComponent = e.Key,
            Part = string.Join(", ", e.Select(x => x.Part)),
            QtyPer = string.Join(", ", e.Select(x => x.QtyPer))
        });

它将为每个FlatComponent创建一个不同的BOM,将PartQtyPer属性与", "连接起来。

您通常可以使用GroupBy在LINQ中完成不同的操作。这将以您为所需结果提供的格式生成结果:

IEnumerable<string[]> asEnumerable = list.GroupBy(bom => bom.FlatComponent).Select(grouping => new string[] { grouping.Key, string.Join(", ", grouping.Select(bom => bom.Part)), string.Join(", ", grouping.Select(bom => bom.QtyPer)) });
string[][] asStringArray = asEnumerable.ToArray();
// For convenience add read-only property
public sealed class BOM
{
    ...
    public string PartAndQuantity { get{return Part + ", " + QtyPer;} }
}
// Group by FlatComponent and then use string.Join:
var result = list.GroupBy (l => l.FlatComponent).Select(
    g => new 
    {
        Flat=g.Key, 
        Parts=string.Join(", ", g.Select (x => x.PartAndQuantity))
    });

这将导致

Flat Parts 
a    "1, 2, 3, 4"
b    "5, 6"
c    "7, 8, 9, 0"

但是你可能想要

var result = list.GroupBy (l => l.FlatComponent).Select(
    g => new 
    {
        Flat=g.Key, 
        Parts=g.Select (x => x.PartAndQuantity).ToList()
    });

我想不出用一个表达式来完成这一切的方法(并且仍然可以理解(,但这里有一些代码可以做你想做的:

[编辑:没有注意到你把零件和数量作为一个字符串,这改变了它:]

var groups = list.GroupBy(item => item.FlatComponent);
List<List<string>> result = new List<List<string>>();
foreach (var group in groups) {
    var current = new List<string>();
    current.Add(group.Key);
    current.AddRange(group.Select(grp => string.Format("{0}, {1}", grp.Part, grp.QtyPer)));
    result.Add(current.Distinct().ToList());
}

最新更新