Selecting a subset of elements in LINQ C# with the TakeWhile operator

The TakeWhile extension method in LINQ is similar to Take. With Take you can specify the number of elements to select from a sequence. In the case of TakeWhile we can specify a condition – a boolean function – instead. The operator will take elements from the sequence while the condition is true and then stop.

Data collection:

string[] bands = { "ACDC", "Queen", "Aerosmith", "Iron Maiden", "Megadeth", "Metallica", "Cream", "Oasis", "Abba", "Blur", "Chic", "Eurythmics", "Genesis", "INXS", "Midnight Oil", "Kent", "Madness", "Manic Street Preachers"
, "Noir Desir", "The Offspring", "Pink Floyd", "Rammstein", "Red Hot Chili Peppers", "Tears for Fears"
, "Deep Purple", "KISS"};

We’ll keep selecting the items until we find one that starts with an ‘E’:

IEnumerable<string> res = bands.TakeWhile(b => b[0] != 'E');
foreach (string s in res)
{
	Console.WriteLine(s);
}

This will print all bands from “ACDC” to and including “Chic”. The last item to be selected will be “Chic”, as the one after that, i.e. Eurythmics starts with an ‘E’.

There’s an overload of TakeWhile where you can pass in the index variable of the loop. The following query will keep selecting the bands until we find one that starts with an ‘E’ OR the loop index exceeds 8:

IEnumerable<string> res2 = bands.TakeWhile((b, i) => b[0] != 'E' && i < 8);
foreach (string s in res2)
{
	Console.WriteLine(s);
}

This time Oasis is the last item to be selected as that is the 8th item, so the “i less than 8” condition was reached first.

View the list of posts on LINQ here.

Introduction to ASP.NET Core part 15: starting with tag helpers

Introduction

In the previous post we discussed a special type of view file in .NET Core MVC called _ViewStart.cshtml. This file can include a C# Razor code block which is executed before the concrete view files are rendered. The most common usage of the view start file is to declare the layout used for that view. That discussion brought us to layout files and how they can help us factor out common HTML markup from the views. Common HTML markup includes menu items, navigation bars, footers and the like. The content of the concrete view file is injected into the layout file using a method called RenderBody. The RenderSection function adds a named section in the layout that the views can implement with a names section directive.

In this post we’ll start covering a new feature in .NET Core MVC called tag helpers. It’s quite a sizable new topic in MVC .NET so we’ll dedicate multiple posts to these helpers since not even experienced ASP.NET MVC developers have been exposed to them.

Read more of this post

Introduction to ASP.NET Core part 14: the view start and the layout files

Introduction

In the previous post we looked at a special kind of view file called _ViewImports.cshtml. It is special in a way that MVC knows about this file and will pick it up during execution. We don’t need to register the file anywhere, we just need to put it in a folder where the views are stored. The view imports file has a very specific role. We can put a number of C# using statements that will be executed in all view cshtml files where the view imports file is applied. We can have multiple _ViewImports file in the project. We can have one in each folder containing the views, like /Views/Books, /Views/Customers etc. and each view file in those folders will pick up the view imports file in that folder. We can also have an overall view imports file in the Views folder as well. That imports file will be applied to every single view within the Views folder and its subfolders.

In this post we’ll look at another special file called _ViewStart.cshtml. We’ll also talk a bit about the layout file since it is strongly related to the view start file.

Read more of this post

Build array index ranges of an integer in C# .NET

Suppose that we have a large array of data heavy objects that are impractical to handle in a single go. Instead we can read batches of the array until all elements have been processed. It can then be useful to build a range of indexes for the objects in the array that we want to extract.

E.g. if an array consists of 357 objects and we want to read at most 100 elements from it in a single batch then the size of the batches will be as follows:

100
100
100
57

…and we want to extract the elements by their indexes as follows:

0, 99
100, 199
200, 299
300, 356

…where the first number is the array start index and the second number is the array end index. Since we’re talking about array indexes the numbers are 0-based of course.

Read more of this post

Introduction to ASP.NET Core part 13: the view imports file

Introduction

In the previous post we looked at data annotation to refine our view models. Data annotations are attributes that can be applied to properties of the view models that are injected into the views. These attributes can be put into three groups: validation, display and data type attributes. Validation attributes can help us filter out the most obvious bad entries from the forms. They can make a field required or they can declare that a property must have a certain minimum and/or maximum value. The Display attribute changes the corresponding property label in the view. The data type attributes declare what kind of editor a certain property needs. E.g. the URL data type gives a hint to the view to render an input of type URL. If the browser has built-in validation for the various input types then it offers an extra layer of validation.

In this post we’ll discuss a very specific view file called the view imports file. As usual we’ll be working in our demo web application DotNetCoreBookstore.

Read more of this post

Joining common values from two sequences using the LINQ Intersect operator

Say you have the following two sequences:

string[] first = new string[] {"hello", "hi", "good evening", "good day", "good morning", "goodbye" };
string[] second = new string[] {"whatsup", "how are you", "hello", "bye", "hi"};

If you’d like to find the common elements in the two arrays and put them to another sequence then it’s very easy with the Intersect operator:

IEnumerable<string> intersect = first.Intersect(second);
foreach (string value in intersect)
{
	Console.WriteLine(value);
}

The ‘intersect’ variable will include “hello” and “hi” as they are common elements to both arrays.

Read more of this post

Introduction to ASP.NET Core part 12: data annotation of view models

Introduction

In the previous post we went through how to insert a new Book entity using a form. We used a view model for this purpose. Two different Create action methods take care of the insertion process in the Books controller. One accepts HTTP GET requests and only presents an empty form with the various book insertion view model properties. The corresponding view has a form that’s built using a Html helper which takes care of setting up the form with the correct naming conventions so that the view model properties can be correctly populated. We also extended our rudimentary layered architecture to simulate that the Book entity is saved in a data store. Finally we also mentioned the usage of the anti-forgery token attribute which guards against a cross site request forgery attack.

In this post we’ll look at how attributes on our attributes can help us refine our view models and how they are rendered in the view.

Read more of this post

An overview of grouping collections with LINQ in .NET

Introduction

The LINQ GroupBy operator is one of the most powerful ones among all LINQ operators. It helps us group elements in a collection in various ways and lets us control the element and result selection process. However, with its many overloads and Func parameters the GroupBy operator can be a bit difficult to understand at first. At least it is more complex than say the Min() and Max() LINQ operators.

This post will go through the GroupBy operator and many of its overloads with a number of examples.

Read more of this post

Introduction to ASP.NET Core part 11: inserting a new Book in a form

Introduction

In the previous post we continued our exploration of MVC in ASP.NET Core by building a details page for the books. We can now click a link for each Book view model in the table and view some more details about the selected book. We also rearranged the code and introduced rudimentary layers of a controller, a service, a domain and a repository for our Book entity. Then we exposed ourselves to the first example of a HTML helper in the Index and Details Razor views with the anchor tag builder. HTML helpers are very useful tools in Razor that help us build dynamic HTML. If you used Razor views before then this is nothing new to you.

In this post we’ll continue on the same path as in the previous part. We’ll build a view to insert a new book entity. We’ll see a couple more HTML helpers to make model binding easier.

Read more of this post

Randomly rearrange a string in .NET C#

Say you’d like to randomly rearrange the contents of a string, i.e. put the constituent characters into new, random positions. The following method can help you with that using a combination of LINQ and Random:

private static string RearrangeString(string startingPoint)
{
	Random num = new Random();
	string rand = new string(startingPoint.
		OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
	return rand;
}

Let’s test it with my name:

string myName = "Andras Nemes";
string myNewName = RearrangeString(myName);

So my new name can be something like “drsNeeAna ms” or “AdaNmesnrs e” or even “ArsNmenda es”, I haven’t decided yet.

Filip Ekberg drew my attention to the following alternative solution:

string rand = new string(startingPoint.OrderBy(x => Guid.NewGuid()).ToArray());

View the list of posts on LINQ here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.