C#在匹配时连接字符串的记录

时间:2015-06-23 12:59:43

标签: c# linq list

我正在生成一组记录,其中每条记录由三个字符串组成。生成的记录数是动态的,因为用户可以根据需要添加。

我需要浏览一组记录,并根据三个字符串中的两个生成/组合记录,并连接第三个字符串。我知道这可能不太清楚,但我提供了一些用户记录集的日期和我需要的结果。

用户生成的记录:

记录1:“ AAA ”,“ BBB ”,“DEF”

记录2:“ AAA ”,“ BBB ”,“QEW”

记录3:“ RRR ”,“ WWW ”,“123”

记录4:“ RRR ”,“ WWW ”,“321”

记录5:“XXX”,“WWW”,“421”

我需要的结果:

记录1:“AAA”,“BBB”,“DEFQEW”

记录2:“RRR”,“WWW”,“123321”

记录3:“XXX,”WWW“,”421“

另外,我应该在哪里存储记录来操纵我想要的日期?

我不熟悉LINQ,所以如果你建议我会欣赏一些例子。谢谢!

修改

我正在数据行中循环生成字符串。我可以将它们存储在列表(字符串)或您建议的任何内容中。

4 个答案:

答案 0 :(得分:4)

如果没有更多背景,很难提出最佳解决方案。一个简单的Linq GroupBy可以解决这个问题:

// Assuming that each array has exactly 3 elements
IEnumerable<string[]> records; // Initialize this
var groupedRecords = records
    .GroupBy(
        // Group the records by the two first values
        r => new { a = r[0], b = r[1] },

        // Concatenate the matching records
        (k, g) => new { k.a, k.b, string.Join("", g.Select(r => r[2]) }
    );

在这个例子中,我假设每条记录只是一个包含3个元素的数组。您可能希望创建一个正确表示您的记录的类型,但代码应该很容易适应。

答案 1 :(得分:2)

如果是IEnumerable<CustomType>CustomType是一个有三个属性的类:

var result = records
    .GroupBy(x => new { x.Prop1, x.Prop2 })
    .Select(g => new CustomType 
    {
        Prop1 = g.Key.Prop1,
        Prop2 = g.Key.Prop2,
        Prop3 = String.Join(", ", g.Select(x => x.Prop3))
    });

如果您的问题中提到的DataTable

var result = table.AsEnumerable()
    .GroupBy(row => new { Col1 = row.Field<string>(0), Col2 = row.Field<string>(1) })
    .Select(g => new
    {
        Col1 = g.Key.Col1,
        Col2 = g.Key.Col2,
        Col3 = String.Join(", ", g.Select(row => row.Field<string>(2)))
    });

答案 2 :(得分:1)

试试这个

{"responseHeader":{"status":0,"QTime":128}}

答案 3 :(得分:0)

// here's the solution thanks to jdweng and Tim - I adjusted it to work with 5 columns based on 3 columns.
var result = toDisplay.AsEnumerable()
             .GroupBy(x => new { Col1 = x.Field<string>("rItem"),
                                 Col2 = x.Field<string>("rMaterial"),
                                 Col3 = x.Field<string>("rSpecs")})
            .Select(g => new
            {
                Col1 = g.Key.Col1,
                Col2 = g.Key.Col2,
                Col3 = g.Key.Col3,
                Col4 = String.Join(", ", g.Select(row => row.Field<string>("rQuantity"))),
                Col5 = String.Join(", ", g.Select(row => row.Field<string>("rOptional"))),
            });