Projection in LINQ C# with the SelectMany operator

The SelectMany operator creates a one-to-many output projection sequence over an input sequence. SelectMany will return 0 or more output elements for every input element. Let’s see an example.

Data source:

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

Consider the following code:

Read more of this post

Converting a sequence of objects into a Lookup with LINQ C#

A Lookup in .NET is one of the lesser known data structures. It is similar to a Dictionary but the keys are not unique. You can insert multiple elements for the same key.

Say you have the following object and collection:

Read more of this post

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

Read more of this post

Projection in LINQ C# with the Select operator

You can use the Select() extension method in LINQ to create an output of type T from an input sequence of type other than T. Let’s see some examples:

Source data:

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

Read more of this post

Concatenate two IEnumerable sequences in C# .NET

We can use the Range method to build two integer sequences as follows:

IEnumerable<int> firstRange = Enumerable.Range(10, 10);
IEnumerable<int> secondRange = Enumerable.Range(5, 20);

You can join the two sequences using the Concat method:

List<int> concatenated = firstRange.Concat(secondRange).ToList();
concatenated.ForEach(i => Debug.WriteLine(i));

You’ll see that the concatenated sequence holds all numbers from the first and the second sequence:

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.

Breaking up a collection into smaller fixed size collections with C# .NET

Occasionally you may need to break up a large collection into smaller size collections or groups. Consider the following integer list:

List<int> ints = new List<int>() { 1, 4, 2, 5, 2, 6, 5, 43, 6, 234, 645, 2, 12, 45, 13, 5, 3 };

The goal is to break up this list into groups of size 5 and if necessary an additional list for the remaining elements. The following generic method will do the trick:

Read more of this post

Finding the maximum value in a sequence with LINQ C#

Finding the maximum value in a sequence can be performed using the Max 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 intMax = integers.Max();

…which gives 3489.

Applying the operator on a list of strings gives the alphabetically maximum 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 stringMax = bands.Max();

…which yields “The Offspring”.

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 maxSingerBirthYear = singers.Max(s => s.BirthYear);

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

String maxSingerName = singers.Max(s => s.FirstName);

…which gives “Ray”.

View the list of posts on LINQ here.

Finding the factorial for a number using Aggregate in LINQ C#

The Aggregate LINQ operator allows you to define your own aggregation function to be performed on a sequence. The function is performed on each element and the result of the function is passed into the next iteration. The final result of the operation is returned at the end.

To calculate the factorial of 5, i.e. 5!, we’d calculate 5x4x3x2x1 or 1x2x3x4x5, doesn’t matter. The first overload of the operator accepts a Function of int, int, int, i.e. it takes two integers and returns an integer.

Here’s how we can calculate 5!:

IEnumerable<int> ints = Enumerable.Range(1, 5);
int factorial = ints.Aggregate((f, s) => f * s);

…which correctly gives 120. ‘f’ is the aggregate value and ‘s’ is the current element in the lambda expression.

The following is performed step by step:

  1. The first iteration passes in f = 1 and s = 2, which yields 1×2 = 2
  2. In the second iteration f is the result of the first iteration, i.e. 2 and s will be the second element, i.e. 3, yielding 2×3 = 6
  3. Then it continues with f = 6 from the second operation and taking 4 from the integer sequence, giving 6×4 = 24
  4. Finally we get 24×5 = 120

View the list of posts on LINQ here.

Finding the average value in a sequence with LINQ C#

The LINQ Average operator can be applied to sequences of numeric types. In its simplest form it returns an average value of type double:

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

…which gives about 552.14.

The operator can be applied to sequences of custom objects using a selector function:

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

double averageBirthYear = singers.Average(s => s.BirthYear);

…which is of course not too meaningful, but you get the idea.

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.