0

I have a list of objects of type quote that I'm passing to a view and showing in a grid. There are a number of drop down lists above the grid for filtering. I want to populate the dropdown lists with a distinct list of valid options based on the data for the grid. The one I'm looking at is 'Created By'.

public IEnumerable<SelectListItem> GetCreatedBy(IEnumerable<Quote> quotes)
{

    var x = quotes.GroupBy(q => new {
             ListValue = q.CreatedBy.samAccountName, 
             ListText = q.CreatedBy.DisplayName})
                .Select(group => new SelectListItem { 
                      Value = group.ListValue, 
                      Text = group.ListText });

        return x;
    }

The error I'm getting is:

'IGrouping<, Quote>' does not contain a definition for 'ListValue' and no extension method 'ListValue' accepting a first argument of type 'IGrouping<, Quote>' could be found (are you missing a using directive or an assembly reference?)

The 'Quote' has a 'User' object as the 'Created By' I want a DropDownList populated with the distinct Users samAccountName and DisplayName without having to re-query to get this list.

I've tried .Distinct() and different versions of the code above with .GroupBy().

I'm new to MVC and really new to lambda expressions. Any help would be very much appreciated.

msd
  • 591
  • 7
  • 23
David
  • 313
  • 3
  • 4
  • You need to specify a column on which you want to groupby. Please refer [this SO](https://stackoverflow.com/questions/7325278/group-by-in-linq) for GroupBy syntax. – Siva Gopal Jun 24 '17 at 04:04
  • Thanks Siva. I saw that example and I think it's different to what I'm trying to do. I tried 'var x = quotes.GroupBy(q => q.CreatedBy.samAccountName, q => q.CreatedBy.DisplayName, (key, g) => new SelectListItem { Value = key, Text = g.First().ToString() });'. This gave me a list of all users, but there were duplicates in there. – David Jun 24 '17 at 06:04

1 Answers1

2

You can use the GroupBy to get the distinct values and then use the first instance in the group to get your values.

var x = quotes
    .GroupBy(q =>
        new 
        {
            q.CreatedBy.samAccountName,
            q.CreatedBy.DisplayName,
        })
    .Select(q => 
        new SelectListItem
        {
            Value = q.First().CreatedBy.samAccountName,
            Text = q.First().CreatedBy.DisplayName,
        });
Lockdowne
  • 474
  • 3
  • 7