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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: