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

时间:2013-04-01 22:26:37

标签: c# linq

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

假设我有以下课程,其中每个BOM有一个或多个FlatComponents,其中PartsQtyPer不同。

示例:

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及其不同的值?

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

我尝试过使用.Distinct(),但我对LINQ很新...

4 个答案:

答案 0 :(得分: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,并使用Part加入QtyPer", "属性。

答案 1 :(得分: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());
}

答案 2 :(得分:0)

您通常可以使用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();

答案 3 :(得分: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()
    });