0

I am trying to make a jquery auto complete where I use a label and value like in this post which means that I need my json in the form of

{ label: 'label text', value: 'value text' }

However I am filtering a list of Employees which is a class with the following structure:

public sealed class Employee
{
    public string Name { get; set; }
    public string PersonnelNumber { get; set; }
    public int RecID { get; set; }
    public string Email { get; set; }
}

So I tried the following Linq to get the format of label, value I needed:

var jsonResult = employees
                  .SelectMany(emp => new { label = emp.Name, value = emp.RecID })
                  .ToList();

Where employees is a list of Employee objects but it is throwing up an build error of

Error 1 The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How do I fix this to get the Name and RecID in a new list of objects with label and value as their output?

Community
  • 1
  • 1
Pete
  • 57,112
  • 28
  • 117
  • 166

2 Answers2

5

I think you just want to use Select here:

var jsonResult = employees
    .Select(emp => new { label = emp.Name, value = emp.RecID })
    .ToList();
Dave Bish
  • 19,263
  • 7
  • 46
  • 63
  • Thanks, this is what I was after. My brain isn't back up to speed after the long easter weekend and thought `SelectMany` was for if you wanted more than one record! – Pete Apr 09 '15 at 07:43
5

SelectMany is for "flattening" a group of collections. Since you just have a single collection just use Select:

var jsonResult = employees.Select(emp => new { label = emp.Name, value = emp.RecID })
                          .ToList();
D Stanley
  • 149,601
  • 11
  • 178
  • 240