Query a Sequence using LINQ

In one of my previous posts, we saw how to Generate Sequence of Float Numbers within a Range using LINQ. In this post, let us see how to query this sequence and extract elements based on a condition

Find First Number in the Sequence

var frstNo = rng.First();
Console.WriteLine("First Number: {0}", frstNo);

Find Last number in the Sequence

var lastNo = rng.Last();
Console.WriteLine("Last Number: {0}", lastNo);

Find First number in a Filtered Sequence

var frstFiltered = rng.Where(n => n > 20).FirstOrDefault();
Console.WriteLine("First Number Greater than 20: {0}", frstFiltered);

Find Last number in a Filtered Sequence

var lastFiltered = rng.Where(n => n < 22).LastOrDefault();
Console.WriteLine("Last Number Lesser than 22: {0}", lastFiltered);

Find Number at a Specified Index

var numIndex = rng.ElementAtOrDefault(15);
Console.WriteLine("Element at index 15: {0}", numIndex);

Here’s the entire code:

LINQ Query Sequence

OUTPUT

LINQ Query Sequence



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: