Tip of the day: Different ways of creating empty List of Objects in c#

It has always been fun to play with C#. In this post we will see that how we can create a list of objects with different approach. Well, in this article’s title i have used the word “empty list of objects” which might be confusing for some developers. Actually, empty list mean – create an object but without assigning any value to the object’s property. So the scenario is – for one of my MVC application I need to bind the 5 empty rows to the kendo grid for bulk insert of the records. So whenever i open that page, kendo grid render 5 empty rows in editable mode.

In this post for better illustration, I have used the example of “Book” i.e. Let say I want to add multiple books for one library management software. So first let’s create one basic POCO class – Book with some properties, looks like following.

public class Book
{
	public string BookName { get; set; } = string.Empty;

	public string Author { get; set; } = string.Empty;

	public string ISBN { get; set; } = string.Empty;
}

So, Let’s begin our journey by exploring the syntax from very basic to some advance level. Before C# 3.0, we used to add objects and initialize collection something like this –

var bookList = new List<Book>();

// Intiazize the object and add it to the collection
var book1 = new Book();
bookList.Add(book1);

var book2 = new Book();
bookList.Add(book2);

and another way is using “for loop” like following –

var bookList = new List<Book>();

// Another one is using for loop
for(int i = 0; i < 2; i++)
{
       bookList.Add(new Book());
}

and another way is using “AddRange()” method – which add the objects to the specified collection.

var bookList = new List<Book>();

// Another one is using AddRange method.
bookList.AddRange(new[] {
					new Book(),
					new Book()
				});

and then c# 3.0 comes with a lot of enhancement and one of them is – Collection Initializers. It is a shortened syntax to create a collection.


// using collection initializer
var bookList = new List<Book>()
{
	new Book(),
	new Book(),
	new Book()
};

In the .Net framework there is one class – Enumerable which resides under “System.Linq” namespace. This class contain some static methods using which we can create the list of objects. So for example – using Enumerable.Repeat() method –


// using Enumerable.Repeat
var bookList = Enumerable.Repeat(new Book(), 2).ToList();

In the above method, the first argument is the object we want to create or repeat. Second argument is the number of times to repeat the object.

Another example is – using Enumerable.Range() method –


// and another one is Enumerable.Repeat
var bookList = Enumerable.Range(1, 2).Select(i => new Book()).ToList();

Well, Range() method generates a collection within a specified range. Kindly note there are so many use cases for this method.

All right, But i’m thinking of to use it in another application, so i decided to make an extension method and make that extension method generic. So here i have created two extension methods. First one will add the “N” number of objects to the list. Second one will return the collection of “N” number of objects.

public static class UtilityExt
{
	///<summary>
	/// Add "N" number of objects to the source list.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	/// <param name="emptySource"></param>
	/// <param name="number">Number of elements to add</param>
	public static void AddNObjectsToCollection<T>(this List<T> emptySource, int number) where T : new()
	{
		emptySource.AddRange(Enumerable.Repeat(new T(), number));
	}

	///<summary>
	/// Returns the collection which contains "N" numbers of elements of type T
	/// </summary>

	/// <typeparam name="T"></typeparam>
	/// <param name="emptySource"></param>
	/// <param name="number">Number of elements to return</param>
	/// <returns></returns>
	public static IList<T> GenerateSpecificNumberOfCollection<T>(this IEnumerable<T> emptySource, int number) where T : new()
	{
		return Enumerable.Repeat(new T(), number).ToList();
	}
}

and you can call the above method like this –

// Calling first method - AddNObjectsToCollection
var bookList = new List<Book>();
bookList.AddNObjectsToCollection(2);

//  ==========  OR   ==========
// Calling second method - GenerateSpecificNumberOfCollection
var bookList = new List<Book>().GenerateSpecificNumberOfCollection(3);

Well, All the syntax mentioned above much affected the readability and repeatability of your code. Any ways, if you have any other way to achieve the same then feel free to add it in comment section and share with other. That’s it for now. Hope you like this post.

Advertisements

Tip of the day: Get the first element from the xml using LINQ to XML

Today, one of my colleague in my office asked me a question that how to get the first element from the XML string. In my previous organization, i had worked with XML but using old methodology. So i thought this is good opportunity to learn and explore LINQ to XML. After some googling i told him that using XElement class of LINQ to XML you can full fill your requirement.

So what exactly the requirement is? Well, In one of my application module, we have save some configuration information in XML format in the database. We need to display the first element of the XML in one label in another web page. So let’s see the XElement class of LINQ to XML in action.

What is XElement?

XElement is one of the fundamental class of LINQ to XML. You can use this class to parse the XML string, create the new element, change the content of the element etc. In this post we’ll use this class to parse the XML string. Well, by not going into much detail let’s see this practically.

Consider i have XML in below format.


<ApplicationName>
  <ModuleConfig AccountNo="Test123" Type="M56X35" Source="XML" PNKNumber="12345" Final="False" />
  <LibraryList>
    <Library1 FolderName="Vendor" />
    <Library12 FolderName="Dealer" />
    <Library123 FolderName="Dealer" />
  </LibraryList>
</ApplicationName>

Now his requirement is –
1). Read the first element from the “LibraryList” tag which is “Library1”.
2). Read the value of attribute “PNKNumber” from “ModuleConfig” tag.

Let’s create the new console application in visual studio.

Here is the solution for the first requirement.


using System.Linq;
using System.Xml.Linq;
using static System.Console;

class Program
{
	static void Main(string[] args)
	{
		string xml = @"<ApplicationName>
						  <ModuleConfig AccountNo=""Test123"" Type=""M56X35"" Source=""XML"" PNKNumber=""12345"" Final=""False"" />
						  <LibraryList>
							<Library1 FolderName=""Vendor"" />
							<Library12 FolderName=""Dealer"" />
						  </LibraryList>
					  </ApplicationName>";

		// First let us parse the xml string using XElement
		var parsedXML = XElement.Parse(xml);

		// Now get the first element from the <LibraryList>  tag.
		string firstElement = parsedXML.Element("LibraryList").Descendants()
                                     .FirstOrDefault().Name.LocalName;
		WriteLine("First Element is - {0}", firstElement);
		ReadLine();
	}
}

Output

First Element is – Library1

Same way to get the 2nd or upto nth tag, you can use the ElementAtOrDefault() method by passing tag index like this –


string elementAt = parsedXML.Element("LibraryList").Descendants()
                  .ElementAtOrDefault(1).Name.LocalName;
WriteLine("Element at Index 1 - {0}", elementAt);
// Output 
// Element at Index 1 - Library12
		
elementAt = parsedXML.Element("LibraryList").Descendants()
            .ElementAtOrDefault(2).Name.LocalName;
WriteLine("Element at Index 2 - {0}", elementAt);
// Output 
// Element at Index 1 - Library123

Here is the solution for the second requirement – Read the value of attribut “PNKNumber” from “ModuleConfig” tag.


using System.Linq;
using System.Xml.Linq;
using static System.Console;

class Program
{
	static void Main(string[] args)
	{
		string xml = @"<ApplicationName>
						  <ModuleConfig AccountNo=""Test123"" Type=""M56X35"" Source=""XML"" PNKNumber=""12345"" Final=""False"" />
						  <LibraryList>
							<Library1 FolderName=""Vendor"" />
							<Library12 FolderName=""Dealer"" />
                            <Library123 FolderName=""Vendor"" />
						  </LibraryList>
					  </ApplicationName>";

		// First let us parse the xml string using XElement
		var parsedXML = XElement.Parse(xml);

		// Read the value of attribute "LNKNumber" from "ModuleConfig" tag.
		// First we check whether "LNKNumber" attribute exists within this "ModuleConfig" tag or not.
		if (parsedXML.Element("ModuleConfig").Attributes().Any(x => x.Name == "PNKNumber"))
		{
			// Now we read the value of attribute "LNKNumber"
			var attrValue = parsedXML.Element("ModuleConfig").Attribute("PNKNumber").Value;
			WriteLine("Attribute value is - {0}", attrValue);
		}
		else
			WriteLine("Attribute PNKNumber does not exists in the xml.");
		
		ReadLine();
	}
}

Output

Attribute value is – 12345

Same way you can check for other attribute also. LINQ to XML really reduce the number of lines of code in your application for complex requirement. My above example is simple, so you can not find some major difference. Any ways that’s it for now. Hope you like this post.

How to achieve UNION ALL and UNION in LINQ

In one of my application, I came to a situation where I had to use UNION ALL like functionality for two enumerable list by using LINQ. So in today’s post we’ll learn about how we can achieve UNION and UNION ALL like functionality using LINQ. You can do a UNION operation using the Union method in LINQ and UNION ALL operation using the Concat method.

Let’s see this practically –

First we will learn about Union method.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionList = productsFromMicrosoft.Union(productsFromGoogle).ToList();

	Console.WriteLine(unionList);
}

UnionList

So as expected, UNION method excludes duplicates from the return set.

Now we will see Concat operator.

static void Main(string[] args)
{
	var productsFromMicrosoft = new List<string>
	{
		"Visual Studio",
		"MS Office",
		"Xbox",
		"Mail Service"  // <-- This product is in both list
	};

	var productsFromGoogle = new new List<string>
	{
		"Google Chrome",
		"Mail Service",  // <-- This product is in both list
		"Blogger"
	};

	var unionAllList = productsFromMicrosoft.Concat(productsFromGoogle).ToList();

	foreach (var product in unionAllList)
	{
		Console.WriteLine(product);
	}
}

UnionAllList

The Concat method differs from the Union method because the Concat() method returns all the original elements in the input sequences. The Union method returns only unique elements.

Reference Link:

That’s it folks. Hope you like this post.