C# how to pass a string from a list of object to a List<T>.Sort() method please?

Arny CP 0 Reputation points
2024-11-08T17:43:43.0266667+00:00

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);
});
C#
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,053 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 67,251 Reputation points
    2024-11-08T22:10:26.8466667+00:00

    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));
    		});
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.