LINQ Extension Methods


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

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.


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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.