bomortensen
bomortensen

Reputation: 3396

Grouping objects by property value

I'm having a bit of trouble figuring this out. I have a list of objects with two properties: Alias and Value

I need to show a list of these objects where the Alias property is grouped by the Value string value. Like this:

MyAlias1, MyAlias2, MyAlias3
     - Value string which is the same for above three aliases

MyAlias4, MyAlias5
     - Value string which is the same for above three aliases

What I have so far is:

var groups = lst.GroupBy(x => new { x.Alias, x.Value });
foreach(var group in groups)
{
    @group.Value
}

But I'm not sure what to do from there, to actually show them as grouped items.

Any help is greatly appreciated!

Upvotes: 0

Views: 2418

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Here is grouping

var groups = lst.GroupBy(x => x.Value);

Here is displaying

@foreach(var group in groups)
{
    <h3>@group.Key</h3>
    <ul>
    @foreach(var alias in group)
    {
        <li>@alias.Alias</li>
    }
    </ul>
}

BTW it's better to create ViewModels in controller, then doing Linq in view:

public class FooViewModel
{
    public string Value { get; set; }
    public string Aliases { get; set; } // if you need concatenated string 
}

In controller:

var model = from x in lst
            group x by x.Value into g
            select new FooViewModel {
               Value = g.Key,
               Aliases = String.Join(", ", g.Select(i => i.Alias))
            };

Upvotes: 0

Brian Geihsler
Brian Geihsler

Reputation: 2087

I think you need to group by the value, then for each group you can print out what you need:

@{ var groups = lst.GroupBy(x => x.Value); }

@foreach (var group in groups)
{
    var aliasString = String.Join(",", group.Select(x => x.Alias));
    <p>@aliasString</p>
    <p>- @group.Key</p>
}

Upvotes: 1

Related Questions