Posted By

stewshack on 06/16/10


Tagged

c Linq


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

maxbaines


Linq to Star Wars


 / Published in: C#
 

This is a simple Linq query against a list of Star Wars characters.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace ExampleLinq
  6. {
  7. public class StarWarsCharacter
  8. {
  9. public string Name { get; set; }
  10. public CharacterType CharacterType { get; set; }
  11. }
  12.  
  13. public enum CharacterType
  14. {
  15. Hero,
  16. Villain
  17. }
  18.  
  19. public class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. List<StarWarsCharacter> starWarsCharacters = new List<StarWarsCharacter>()
  24. {
  25. new StarWarsCharacter { Name = "Luke", CharacterType = CharacterType.Hero },
  26. new StarWarsCharacter { Name = "Vader", CharacterType = CharacterType.Villain },
  27. new StarWarsCharacter { Name = "Obi-Wan", CharacterType = CharacterType.Hero },
  28. new StarWarsCharacter { Name = "Tarkin", CharacterType = CharacterType.Villain }
  29. };
  30. var heroes = from s in starWarsCharacters
  31. where s.CharacterType == CharacterType.Hero
  32. select s.Name;
  33. heroes.ToList<string>().ForEach(h => Console.WriteLine(h));
  34. }
  35. }
  36. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: freshclickmedia on June 17, 2010

Works, but would have been better if CharacterType was an enum.

Posted By: stewshack on June 24, 2010

Amen to that brother! I want to rid the world of magic strings too. Thanks for the feedback.

You need to login to post a comment.