Linq to Star Wars


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

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


Copy this code and paste it in your HTML
  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

You need to login to post a comment.