Created
July 23, 2015 10:47
-
-
Save childnode/75a3845229b2e69a7f19 to your computer and use it in GitHub Desktop.
Alphanumeric sorting in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary>simple Value Object</summary> | |
public class MyDataObject | |
{ | |
public string Name { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using NUnit.Framework; | |
[TestFixture] | |
public class SortTest | |
{ | |
[Test] | |
public void SortListTest() | |
{ | |
var ui = new UsageClass(); | |
var unsortedList = new List<MyDataObject>() | |
{ | |
new MyDataObject() { Name = "wasser" }, | |
new MyDataObject() { Name = "Aaab" }, | |
new MyDataObject() { Name = "W93" }, | |
new MyDataObject() { Name = "wässer" }, | |
}; | |
var current = ui.GetSortedNameList(unsortedList); | |
var unsortedNameList = unsortedList.Select(s => s.Name).ToList(); | |
var expected = new List<string>() | |
{ | |
"Aaab", | |
"W93", | |
"wasser", | |
"wässer", | |
}; | |
Assert.AreNotEqual(unsortedNameList, expected); | |
Assert.AreEqual(current, expected); | |
for (int i = 0; i < current.Count; i++) | |
{ | |
Assert.AreSame( | |
current[i], | |
expected[i], | |
string.Format( | |
"found `{0}` at pos #{1} but expected to be found at pos #{2}", | |
current[i], | |
i, | |
expected.FindIndex(s => s.Equals(current[i])))); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.Linq; | |
public class UsageClass | |
{ | |
public List<string> GetSortedNameList(IEnumerable<MyDataObject> objList) | |
{ | |
if (objList == null) | |
{ | |
return new List<string>(); | |
} | |
return objList | |
.OrderBy(s => s.Name, StringComparer.Create(CultureInfo.CurrentCulture, true)) | |
.Select(p => p.Name) | |
.ToList(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment