C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,061 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
How to pass a string (level) from a list of object to a List<T>.Sort() method please?
Data:
List<DirItem> items = new List<DirItem>
{
new DirItem { level="3.5-1", name="Hi", description="Hello" },
new DirItem { level="3.5", name="Hi", description="Hello" },
new DirItem { level="4.1.1-1", name="Hi", description="Hello" }
};
Use this to sort strings like 1.1.-1
items.Sort((x, y) => // How do I do this bit? Passing 'level' as the string to Sort please?
{
var xparts = x.Split('.');
var yparts = y.Split('.');
for (int i = 0; i < xparts.Length; i++)
{
if (i >= yparts.Length)
return 1;
var xval = int.Parse(xparts[i]);
var yval = int.Parse(yparts[i]);
if (xval != yval)
return xval.CompareTo(yval);
}
return xparts.Length.CompareTo(yparts.Length);
});
split by ".", then by "-" then compare
items.Sort((a,b) =>
{
Func<int[], int[], int> CompareArrays = (a1, a2) =>
{
for (var i = 0; i < a1.Length; ++i)
{
if (i >= a2.Length || a1[i] > a2[i])
return 1;
if (a1[i] < a2[i])
return -1;
}
return a2.Length > a1.Length ? -1 : 0;
};
Func<string, int[]> LevelToArray = (s) => s.Split('.')
.SelectMany(e => e.Split('-'))
.Select(e => int.Parse(e)).ToArray();
return CompareArrays(LevelToArray(a.level), LevelToArray(b.level));
});