The Self-Taught Programmer

Recipes from real-world experience with asp.net.

Posts Tagged ‘Generic List

How to Sort a Generic List of Objects

leave a comment »

The Situation

You are trying to sort a Generic List of Objects based on a property of the Objects.

A Solution

There are two easy options for sorting a Generic List populated with Objects: in place and sorting to a new List. Use Linq.

“In Place” sorting of an existing List (the code below only works with text fields):

using System.Linq;

Users.Sort((a, b) => string.Compare(a.LastName, b.LastName));

Sort a List to a new list:

List<Users> UserList = Users.OrderBy(o => o.LastName).ToList();
Advertisements

Written by Jim McMullen

January 2, 2014 at 5:08 pm

Posted in How-To

Tagged with ,

How to Split a String into a Generic List Rather Than an Array

leave a comment »

The Situation

You want to split a string, but the C# split() function returns a string[] array. You want a List<string> instead.

A Solution

If you are using .Net 3.5 or later, use Linq extensions:

using System.Linq;

string csvString = "a,b,c,d,e";
List<string> items = csvString.Split(',').ToList();

Written by Jim McMullen

May 29, 2013 at 5:08 pm

Posted in How-To

Tagged with ,

How to Convert a Generic List to a Comma-Delimited List

leave a comment »

The Situation:

You have a List<string> and need to convert it to a comma-delimited list (for display or storage).

A Solution:

This is a great example of how C# has improved over the years. I found this solution in this StackOverflow discussion and don’t want to lose it, so I am copying it here for reference.

List<string> strings = <code>...;

// .NET 2.0:
string joined = string.Join(",", new List<string>(strings).ToArray());

// .NET 3.5:
string joined = string.Join(",", strings.ToArray());

// .NET 4.0:
string joined = string.Join(",", strings);

Thanks to Jon Skeet, Xavier Poinas and the rest of the guys that participated in that discussion. Gotta love StackOverflow!

Written by Jim McMullen

March 25, 2013 at 11:32 am

Posted in How-To

Tagged with ,

How to Find the Index of an Object in a List

leave a comment »

The Situation

You are trying to find out if an object exists in a List object.

A Solution

Use Linq. The example below looks for a User object in a List<User> by searching for the UserName:

private int FindObjectInList(List<User> list, string uName)
{
    return list.FindIndex(s => s.UserName == uName);
}

Written by Jim McMullen

February 1, 2013 at 10:23 pm

Posted in How-To

Tagged with ,

How to Find the Index of a String in a List

leave a comment »

The Situation

You are trying to find out if a string exists in a List object.

A Solution

You could use a Find with a predicate, or try the simple method below.

private int FindStringInList(List<string> list, string str)
{
    return list.FindIndex(s => s == str);
}

Written by Jim McMullen

October 17, 2011 at 3:54 pm

Posted in How-To

Tagged with ,