Cheyne
Cheyne

Reputation: 2117

LINQ Grouping or Splitting

Im having an issue doing something thats probably pretty simple.

My LINQ query is returning a result set of 10 objects.

Something like:

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

What I need to do, is to group these so that there are only 2 rows, ie one per Name, but have the ones with "Action: bbb" move into a different column. So the output would be:

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

Can anyone explain to me how I might do that?

Cheers

Upvotes: 0

Views: 92

Answers (2)

RePierre
RePierre

Reputation: 9566

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

The query above assumes that you have only two rows for each name; if you have multiple rows per name, you can take the second Action/Id value by using .Skip(1).Take(1) instead of .Last()

Upvotes: 1

Brad Rem
Brad Rem

Reputation: 6026

I don't think there's a real simple way to do it. I've connocted this, though, which might get you started:

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

Run it here: http://ideone.com/8UTxr

Upvotes: 1

Related Questions