Anonymous types as properties in LINQ


/ Published in: C#
Save to your folder(s)

Notice that the property name declared (foo) is used later in the query for the ORDERBY operator and SELECT statement.


Copy this code and paste it in your HTML
  1. using (var context = new SampleEntities())
  2. {
  3. var contacts = from c in context.Contacts
  4. where c.FirstName == "Robert"
  5. let foo = new
  6. {
  7. ContactName = new { c.Title, c.LastName, c.FirstName },
  8. c.Addresses
  9. }
  10. orderby foo.ContactName.LastName
  11. select foo;
  12.  
  13. foreach (var contact in contacts)
  14. {
  15. var name = contact.ContactName;
  16. Console.WriteLine("{0} {1} {2}: # Addresses {3}",
  17. name.Title.Trim(), name.FirstName.Trim(),
  18. name.LastName.Trim(), contact.Addresses.Count());
  19. }
  20. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.