Posted By

rengber on 04/20/09


Tagged

lambda Linq IEnumerable ExtensionMethod


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

ddevening
umang_nine


LINQ Extension Methods


 / Published in: C#
 

LINQ Extension method called with delegate, anonymous delegate, and lambda delegate.

Note that this only returns a "default" in the sense that it does not throw an exception if no item in the source matches the selection criteria. .First() does throw an exception in this case.

  1. [TestMethod]
  2. public void DemoLINQExtensionMethods()
  3. {
  4. List<int> ints = new List<int>(new int[] { 1, 11, 12 });
  5. //Standard Delegate
  6. int val = ints.FirstOrDefault(ThisOneGoesToEleven);
  7. Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
  8. //Using Anonymous Method
  9. val = ints.FirstOrDefault(delegate(int i) { return i == 11; });
  10. Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
  11. //Using equivalent Lambda syntax
  12. val = ints.FirstOrDefault(x => x == 11);
  13. Assert.IsTrue(val == 11, "Eleven was not found. Value = " + val.ToString());
  14. }
  15. private bool ThisOneGoesToEleven(int volume)
  16. {
  17. return volume == 11;
  18. }

Report this snippet  

You need to login to post a comment.