1

I need help in getting value from my linq query. Using firstordefault()

var item = (from o in db.Employee
                    join a in db.EmployeeLineManager on o.Id equals a.EmployeeID
                    where o.Id == Id
                    select new
                    {
                        AddedBy = o.LastName + " " + o.FirstName,
                        LineManagerId = a.LineManagerId,
                        Email = o.Email
                    }).FirstOrDefault();

I can get what is in the item(e.g if I want to get email, I can use item.Email)

But, if I use ToList()

var item = (from o in db.Employee
                    join a in db.EmployeeLineManager on o.Id equals a.EmployeeID
                    where o.Id == Id
                    select new
                    {
                        AddedBy = o.LastName + " " + o.FirstName,
                        LineManagerId = a.LineManagerId,
                        Email = o.Email
                    }).ToList();

How do I get value from the item(e.g i want to get the Email, item.Email does not work, please what can I use to get the values?

  • 1
    Possible duplicate of [Return list of specific property of object using linq](https://stackoverflow.com/questions/11574376/return-list-of-specific-property-of-object-using-linq) – vahdet May 15 '19 at 12:17
  • 1
    In the second case `item` is a *list* of items. It should be named `items` to avoid any confusion. You can access its contents just like any other list or array, eg `items[0].Email` or `foreach(var item in items){ item.Email.....}`. – Panagiotis Kanavos May 15 '19 at 12:20
  • @PanagiotisKanavos thank you – Emmanuel Ikechukwu May 15 '19 at 12:46

1 Answers1

5

In the first example, item is a single object. In the second example it is a list of objects. (As the name implies, ToList converts the results to a list.)

List<T> has no property called Email. But it does contain zero or more elements which do in this case.

So you might do something like:

item.FirstOrDefault().Email

or perhaps:

item[0].Email

or you could loop over the list, etc.

A couple things to keep in mind:

  1. item is the wrong name at this point. It's a collection, so call it items. Variable names are important for you to understand your own code.
  2. The list might be empty, in which case both of the above example usages would throw an exception. You should always do some measure of null checking. For example:

    items.FirstOrDefault()?.Email
    
David
  • 208,112
  • 36
  • 198
  • 279
  • 2
    In regards to the null checking, an exception may be the desired outcome here. But you would expect a clear exception message (and/or type), rather than a null reference exception which doesn't tell the consumer exactly _what_ went wrong. So a check+clear message is still needed, but that doesn't inherently mean you need to avoid exceptions as a whole. – Flater May 15 '19 at 12:21