Finding the minimum value in a sequence with LINQ C#

Finding the minimum value in a sequence can be performed using the Min LINQ operator. In it simplest, parameterless form it works on numeric sequences like this:

List<int> integers = new List<int>() { 54, 23, 76, 123, 93, 7, 3489 };
int intMin = integers.Min();

…which gives 7.

Applying the operator on a list of strings gives the alphabetically minimum value in the list:

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"};
string stringMin = bands.Min();

…which yields Abba.

The operator can be applied to sequences of custom objects:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int BirthYear { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
{
	new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
	, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
	, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
	, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
	, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
};

int minSingerBirthYear = singers.Min(s => s.BirthYear);

We applied a selector function to find the minimum birth year, i.e. 1950. We can find the minimum first name alphabetically speaking:

String minSingerName = singers.Min(s => s.FirstName);

…which gives “Chuck”.

View the list of posts on LINQ here.

Getting the first element from a sequence in LINQ C#

Say you have the following object sequence:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int BirthYear { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
			{
				new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
				, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
				, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
				, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
				, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
			};

If you just want to get the very first element from this sequence with no query then you can use the First operator:

Singer singer = singers.First();
Console.WriteLine(singer.LastName);

This will select Freddie Mercury from the list. You can also send an item selector to get the first element which matches the query:

Singer singer = singers.First(s => s.Id == 2);
Console.WriteLine(singer.LastName);

…which returns Elvis Presley.

A caveat is that the First operator throws an InvalidOperationException if there’s no single matching record:

Singer singer = singers.First(s => s.Id == 100);

To avoid this scenario you can use the FirstOrDefault operator which returns the default value of the required object if there’s no matching one. Therefore “singer” in the above example will be null:

Singer singer = singers.FirstOrDefault(s => s.Id == 100);
Console.WriteLine(singer == null ? "No such singer" : singer.LastName);

…which prints “No such singer”.

View the list of posts on LINQ here.

Retrieving an element from a sequence with an index in LINQ C#

Say you have the following Singer object and sequence of Singers:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int BirthYear { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
		{
			new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
			, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
			, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
			, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
			, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
		};

Say you want to get to the second element of the singers sequence. You can use the ElementAt operator to achieve that. As all arrays and lists are 0 based, then the second element has index = 1:

Singer singer = singers.ElementAt(1);
Console.WriteLine(singer.LastName);

The operator has found Elvis Presley. If there’s no element at the specified index then an ArgumentOutOfRangeException is thrown. To avoid that you can use the ElementAtOrDefault operator instead:

Singer singer = singers.ElementAtOrDefault(100);
Console.WriteLine(singer == null ? "No such singer" : singer.LastName);

…which prints “No such singer”.

View the list of posts on LINQ here.

Building a uniform sequence using the Repeat operator in LINQ C#

Using the Repeat operator you can create sequences where the same input object is repeated a number of times.

Its usage is very simple. Say you need a list of integers with number 1 repeated 10 times:

IEnumerable<int> integers = Enumerable.Repeat<int>(1, 10);
foreach (int i in integers)
{
	Console.WriteLine(i);
}

…which simply prints “1” 10 times.

Be careful with reference types. If you want identical objects in the sequence that can be modified separately then use the new keyword directly in the Repeat method:

IEnumerable<Band> bands = Enumerable.Repeat<Band>(new Band() { Name = "Band" }, 10);

Otherwise all objects will have the same reference:

Band band = new Band() { Name = "Band" };
IEnumerable<Band> bands2 = Enumerable.Repeat<Band>(band, 10);

…and modifying one will modify all references.

View the list of posts on LINQ here.

Getting the last element from a sequence with LINQ C#

Say you have the following object sequence:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public int BirthYear { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
			{
				new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury", BirthYear=1964}
				, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley", BirthYear = 1954}
				, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry", BirthYear = 1954}
				, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles", BirthYear = 1950}
				, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie", BirthYear = 1964}
			};

If you just want to get the very last element from this sequence with no query then you can use the Last operator:

Singer singer = singers.Last();
Console.WriteLine(singer.LastName);

This will select David Bowie from the list. You can also send an item selector to get the last element which matches the query:

Singer singer = singers.Last(s => s.BirthYear == 1954);
Console.WriteLine(singer.LastName);

…which returns Chuck Berry.

A caveat is that the Last operator throws an InvalidOperationException if there’s no single matching record:

Singer singer = singers.Last(s => s.BirthYear == 2000);

To avoid this scenario you can use the LastOrDefault operator which returns the default value of the required object if there’s no matching one. Therefore “singer” in the above example will be null:

Singer singer = singers.LastOrDefault(s => s.BirthYear == 2000);
Console.WriteLine(singer == null ? "No such singer" : singer.LastName);

…which yields “No such singer”.

You can view all LINQ-related posts on this blog here.

Convert a sequence of objects to a sequence of specific type in LINQ .NET

In the posts on LINQ on this blog we’ve seen some ways to convert a sequence of type A to a sequence of type B. This particular post deals with converting a sequence of objects to a sequence of some specific type.

Say that you have some old style collection such as this:

ArrayList stringList = new ArrayList() { "this", "is", "a", "string", "list" };

You can easily turn this into a proper string list using the Cast operator:

IEnumerable<string> stringListProper = stringList.Cast<string>();
foreach (string s in stringListProper)
{
	Console.WriteLine(s);
}

…which results in…

this
is
a
string
list

It works of course for any object type, even for your custom objects.

However, what if you have the following starting point?

ArrayList stringList = new ArrayList() { "this", "is", "a", "string", "list", 1, 3, new Band() };

The integers and the Band object are not of type string so the Cast operator will throw an InvalidCastException. This is where the OfType extension enters the picture. It does the same job as Cast but it ignores all objects that cannot be converted:

IEnumerable<string> stringListProper = stringList.OfType<string>();
foreach (string s in stringListProper)
{
	Console.WriteLine(s);
}

…which yields the same output as above without throwing any exception.

So in case you need to deal with sequences you don’t control and whose content type you cannot be sure of then you should probably use the OfType extension.

You can view all LINQ-related posts on this blog here.

Introduction to forms based authentication in ASP.NET MVC5 Part 3

Introduction

In the previous post we started digging into the components around Identity in MVC5. We looked at the default database and the Microsoft.AspNet.Identity.Core. We also saw how the MVC5 template with Forms based authentication creates a default UserManager class which can handle user creation, login, updates, claims etc.

We’ll continue our discussion with some other components around Identity in an MVC5 project.

We’ll build on the demo application from the previous two parts of this series.

EntityFramework

EntityFramework is the default choice for storing users in an MVC5 project. As far as identity is concerned EF is encapsulated in the Microsoft.AspNet.Identity.EntityFramework package. Do you recall the interfaces around user management in the Core assembly? IUserStore, IUserLoginStore, IUserClaimsStore etc. The EntityFramework assembly provides the out-of-the-box concrete implementation of each of those abstractions. Examples:

  • IdentityUser implements IUser
  • IdentityRole implements IRole
  • UserStore implements IUserStore, IUserLoginStore, IUserClaimsStore etc., so it contains a large amount of methods and properties which are implementations of the interfaces

IdentityUser and IdentityRole are entities that depend on EF for their persistence mechanism. Recall the database that MVC5 created for us in the local DB. Those are the DB representations of these identities. In AccountController.cs this UserStore is passed to the constructor of UserManager which in turn is passed into the constructor of AccountController. The UserManager will be responsible for all user-related operations through the UserStore implementation: insert, update, delete, add to role, read claims etc. If you navigate to AccountController.cs then you’ll see that the type of the user in the type definition is ApplicationUser. So what’s IdentityUser? If you locate the ApplicationUser class in Models/IdentityModels.cs then you’ll see that it derives from IdentityUser.

You can use the ApplicationUser class to extend the functionality of the default IdentityUser entity in EF with your custom properties.

There’s an additional important object in IdentityModels.cs: ApplicationDbContext which derives from IdentityDbContext of ApplicationUser. IdentityDbContext in turn derives from DbContext which is the standard object context in EntityFramework. Hence ApplicationDbContext is also a DbContext but it has access to the User related information that IdentityDbContext carries. We said that Users and Roles are entities so it’s just as well that ApplicationDbContext gets access to them. The constructor of the ApplicationDbContext object defines the name of the connection string, which is DefaultConnection. We saw this in the previous post but now we know where it is defined. In case you’ve renamed your connection string in web.config then you need to rename it here too.

ApplicationDbContext is also where you can add your custom DbSets so that EF can create the tables for you. We’ll go into EntityFramework in the series after this one so let’s not dive into that topic too much. It suffices to say the if you have a Customer domain then you can add a DbSet of Customer like this directly in ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

	public DbSet<Customer> Customers { get; set; }
}

If you go back to AccountController.cs you’ll notice that an ApplicationDbContext object is passed into the constructor of UserStore. Now we know that ApplicationDbContext derives from IdentityDbContext. IdentityDbContext is the EF object context which will carry out the actual DB operations of SELECT, UPDATE, DELETE etc. If you’re familiar with EF then this object context class will sound familiar.

You’ll also notice the TUser generic type argument. The actual type provided in all cases is ApplicationUser. You can define your own user type if you like but the following definitions force your implementation to implement IUser:

public class UserStore<TUser> : IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserStore<TUser>, IDisposable where TUser : global::Microsoft.AspNet.Identity.EntityFramework.IdentityUser

public class UserManager<TUser> : IDisposable where TUser : global::Microsoft.AspNet.Identity.IUser

I think it’s fine to have that constraint as IUser is an abstraction with minimal content:

string Id { get; }
string UserName { get; set; }

IdentityDbContext also provides the mapping between the entity classes and their DB representations. It also ensures that the tables are properly created when they are needed for the first time.

In summary we can say the Microsoft.AspNet.Identity.EntityFramework library provides the EntityFramework implementation of the abstractions in the Microsoft.AspNet.Identity.Core library. Let’s look at the concrete classes in some more detail.

First go at customisation

We’ve discussed the UserManager in some detail in the previous and this post. The Login action is represented by two methods in AccountController.cs:

[AllowAnonymous]
public ActionResult Login(string returnUrl)

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

The GET action method on top is fired when the user navigates to the Login page with the login form. The upon pressing the Log in button the POST action is invoked which accepts the LoginViewModel which in turn has 3 properties:

public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }

You’ll see that these are populated from the form. The POST Login method is the more interesting one as far as Identity is concerned. In the body of the method the UserManager will try to find the ApplicationUser with the FindAsync method. If the user exists, i.e. it is not null, then she is signed in and redirected to the return url. Otherwise the ModelState is invalidated.

Let’s see how we can add our custom property to the ApplicationUser object. Locate the object and add the following property:

public class ApplicationUser : IdentityUser
{
	public string FavouriteProgrammingLanguage { get; set; }
}

We’ll need to extend the corresponding view model if we want to collect this information from the user. Locate RegisterViewModel in Models/AccountViewModel.cs. It will have 3 fields: username, password and confirm password. Add a 4th one:

[Required]
[Display(Name="Favourite programming language")]
[DataType(DataType.Text)]
public string FavouriteProgrammingLanguage { get; set; }

Next open Register.cshtml in the Views/Account folder. You’ll see a form-group div where the user has to confirm the password. Just underneath add a new div:

<div class="form-group">
        @Html.LabelFor(m => m.FavouriteProgrammingLanguage, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.FavouriteProgrammingLanguage, new { @class = "form-control" })
        </div>
</div>

Back in AccountController.cs locate the POST Register method that accepts a RegisterViewModel object. You’ll see the following bit of code after the if statement:

var user = new ApplicationUser() { UserName = model.UserName };

Extend the object as follows:

var user = new ApplicationUser() { UserName = model.UserName, FavouriteProgrammingLanguage = model.FavouriteProgrammingLanguage };

Let’s run the app and see what happens. Don’t log in with the user you created before. Instead, click on the Register link. The Register page should show the new text field. Create a new user, provide a programming language and press the Register button and.. …the yellow screen of death appears:

Yellow screen of death for code first migration

We’ve changed the entity structure but the database isn’t recreated for us on the fly of course. We’ll rectify this problem in the next post which will discuss DB migrations with EF in the User data context. We’ll revisit migrations in a greater detail in a planned series on EntityFramework which will follow this series.

The new field needs to be included elsewhere like on the Manage.cshtml view for completeness, but you can do that as an exercise.

Read the next post in this series here.

You can view the list of posts on Security and Cryptography here.

Determine the presence of an element in a sequence with LINQ C#

Say we have the following string list:

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"};

The Any operator in LINQ has two versions. The paramaterless one simply returns true if the sequence contains at least one element:

bool exists = bands.Any();
Console.WriteLine(exists);

This yields true. The more exciting version of Any is where you can specify a filter in form of an element selector lambda:

bool exists = bands.Any(b => b.Length == 4);
Console.WriteLine(exists);

This gives true as we have at least one element which consists of 4 characters. The below query returns false:

bool exists = bands.Any(b => b.EndsWith("hkhkj"));
Console.WriteLine(exists);

You can view all LINQ-related posts on this blog here.

Converting a sequence to a dictionary using the ToDictionary LINQ operator

Say you have a sequence of objects that you’d like to convert into a Dictionary for efficient access by key. Ideally the objects have some kind of “natural” key for the dictionary such as an ID:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

IEnumerable<Singer> singers = new List<Singer>() 
		{
			new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury"} 
			, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley"}
			, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry"}
			, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles"}
			, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie"}
		};

It’s easy to create a singers dictionary from this sequence:

Dictionary<int, Singer> singersDictionary = singers.ToDictionary(s => s.Id);
Console.WriteLine(singersDictionary[2].FirstName);

Basic ToDictionarty operator

You supply the key selector as the argument to the operator, which will be the key of the dictionary. The operator will throw an ArgumentException if you’re trying to add two objects with the same key. Example:

return new List<Singer>() 
		{
			new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury"} 
			, new Singer(){Id = 1, FirstName = "Elvis", LastName = "Presley"}
			, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry"}
			, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles"}
			, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie"}
		};

There are two singers with id = 1 which will cause an exception when it’s Elvis’ turn to be inserted into the dictionary.

The ToDictionary operator has an overload which allows you to change the elements inserted into the dictionary. Say you’d like to have the id as the key but only the last name as the value. You can do like this:

Dictionary<int, string> singersDictionaryNames = 
        singers.ToDictionary(s => s.Id, si => string.Format("Last name: {0}", si.LastName));
Console.WriteLine(singersDictionaryNames[2]);

Overloaded ToDictionary operator

You can view all LINQ-related posts on this blog here.

Finding unique values using the LINQ Distinct operator

Extracting unique values from a sequence of objects in LINQ is very easy using the Distinct operator. It comes in two versions: one with a default equality comparer and another which lets you provide a custom comparer.

We’ll use the following collection for the first demo:

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"};

These are all unique values so let’s create some duplicates:

IEnumerable<string> bandsDuplicated = bands.Concat(bands);

The first prototype of Distinct will compare the string values using the standard default string comparer as all elements in the array are strings. The following bit of code will find the unique values and print them on the console:

IEnumerable<string> uniqueBands = bandsDuplicated.Distinct();
foreach (String unique in uniqueBands)
{
	Console.WriteLine(unique);
}

Distinct operator with default comparer

In case you have a sequence of custom objects then it’s a good idea to let the Distinct operator know how to define if two objects are equal. Consider the following object:

public class Singer
{
	public int Id { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
}

…and the following collection:

IEnumerable<Singer> singers = new List<Singer>() 
			{
				new Singer(){Id = 1, FirstName = "Freddie", LastName = "Mercury"} 
				, new Singer(){Id = 2, FirstName = "Elvis", LastName = "Presley"}
				, new Singer(){Id = 3, FirstName = "Chuck", LastName = "Berry"}
				, new Singer(){Id = 4, FirstName = "Ray", LastName = "Charles"}
				, new Singer(){Id = 5, FirstName = "David", LastName = "Bowie"}
			};

The following comparer will compare the Singer objects by their IDs:

public class DefaultSingerComparer : IEqualityComparer<Singer>
{
	public bool Equals(Singer x, Singer y)
	{
		return x.Id == y.Id;
	}

	public int GetHashCode(Singer obj)
	{
		return obj.Id.GetHashCode();
	}
}

We create some duplicates:

IEnumerable<Singer> singersDuplicates = singers.Concat(singers);

…and then select the unique values:

IEnumerable<Singer> uniqueSingers = singersDuplicates.Distinct(new DefaultSingerComparer());
foreach (Singer singer in uniqueSingers)
{
	Console.WriteLine(singer.Id);
}

Distinct operator with custom comparer

You can view all LINQ-related posts on this blog 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.