0

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

假设我有以下课程,其中每个课程BOM都有一个或多个FlatComponents不同的Partsand QtyPer

例子:

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"));

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

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

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

4

4 回答 4

1

试试这个:

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))
        });

它将BOM为每个创建一个不同的FlatComponent,将PartQtyPer属性与", ".

于 2013-04-01T22:52:57.153 回答
0

我想不出一种方法可以在一个表达式中完成所有操作(并且仍然可以理解),但是这里有一些代码可以满足您的需求:

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

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());
}
于 2013-04-01T22:47:49.473 回答
0

您通常可以在 LINQ 中使用GroupBy. 这会以您为所需结果提供的格式生成结果:

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();
于 2013-04-01T22:47:50.737 回答
0
// 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()
    });
于 2013-04-01T22:50:52.737 回答