LINQ分组或分裂

时间:2012-05-02 17:05:02

标签: linq c#-4.0 entity-framework-4

我有一个问题可能很简单。

我的LINQ查询返回了10个对象的结果集。

类似的东西:

Name: Bill, Action: aaa, Id: 832758
Name: Tony, Action: aaa, Id: 82fd58
Name: Bill, Action: bbb, Id: 532758
Name: Tony, Action: bbb, Id: 42fd58

我需要做的是将这些组分组,使得只有2行,即每个名称一行,但是具有“Action:bbb”的行会移动到不同的列中。所以输出将是:

Name: Bill, Action: aaa, Action_2: bbb, Id: 832758, Id_2: 532758
Name: Tony, Action: aaa, Action_2: bbb, Id: 82fd58, Id_2: 42fd58

任何人都可以向我解释我会怎么做吗?

干杯

3 个答案:

答案 0 :(得分:1)

我认为没有一种真正简单的方法可以做到这一点。不过,我已经把它搞砸了,这可能会让你开始:

var myData = new []
{
    new { Name = "Bill", Action="aaa", Id = "832758" },
    new { Name = "Tony", Action="aaa", Id = "82fd58" },
    new { Name = "Bill", Action="bbb", Id = "532758" },
    new { Name = "Tony", Action="bbb", Id = "42fd58" }
};

// group all the Names together
var result = from m in myData
group m by m.Name into names
orderby names.Key
select names;

// go through each Name group and create the output string to store in sbLines
var sbLines = new StringBuilder();
foreach (var name in result)
{
    var sb = new StringBuilder();
    sb.AppendFormat("Name: {0}, ", name.Key);

    int count = 1;
    foreach (var item in name)
    {
        if(count > 1)
            sb.AppendFormat("Action_{0}: {1}, ", count, item.Action);
        else
            sb.AppendFormat("Action: {0}, ", item.Action);
        count++;
    }

    count = 1;
    foreach (var item in name)
    {
        if(count > 1)
            sb.AppendFormat("Id_{0}: {1}, ", count, item.Id);
        else
            sb.AppendFormat("Id: {0}, ", item.Id);
        count++;
    }

    sbLines.Append(sb.ToString().Trim(new char[] { ' ',',' }));
    sbLines.Append(Environment.NewLine);
}

Console.WriteLine(sbLines.ToString());

在此处运行:http://ideone.com/8UTxr

答案 1 :(得分:1)

var myData = new [] 
{ 
    new { Name = "Bill", Action="aaa", Id = "832758" }, 
    new { Name = "Tony", Action="aaa", Id = "82fd58" }, 
    new { Name = "Bill", Action="bbb", Id = "532758" }, 
    new { Name = "Tony", Action="bbb", Id = "42fd58" } 
}; 

var result = myData
    .GroupBy(x=>x.Name)
    .Select(g=>new
    {
        Name = g.Key,
        Action = g.First().Action,
        Action_2 = g.Last().Action,
        Id = g.First().Id,
        Id_2 = g.Last().Id
    });

上面的查询假设每个名称只有两行;如果每个名称有多个行,则可以使用Action代替Id

来获取第二个.Skip(1).Take(1) / .Last()

答案 2 :(得分:0)

感谢您的反馈。他们都很有帮助。最终,我能够更轻松地使用RePierre的解决方案。

我也找到了通过将相同的数据集连接回自己的过滤来实现这一目的。