Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c# - Order lists lexicographically using Linq

I have a list of lists (int type). Example:

1 5 7 2 3
1 7
1 4 1 2 3 4

And i want to order them lexicographically.

Example output:

1 4 1 2 3 4
1 5 7 2 3
1 7

And I'm asking because I can't figure out how. Google has nothing interesting to say.

question from:https://stackoverflow.com/questions/65907527/order-lists-lexicographically-using-linq

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can implement IComparer<List<int>> and use it with LINQ's OrderBy method:

public class ListComparer : IComparer<List<int>> {
    public int Compare(List<int> x, List<int> y) // > 1, == 0, < -1
        => x.Zip(y, (x1, y1) => (x1,y1))
            .Where(xy => xy.x1 != xy.y1)
            .Select(xy => xy.x1 > xy.y1 ? 1 : -1)
            .DefaultIfEmpty(x.Count > y.Count ? 1 : x.Count == y.Count ? 0 : -1)
            .First();
}

NOTE: If a list is a prefix of another the list, the shorter list is sorted first. If two lists are equal, they remain in their original order.

With this, you can

var ans = src.OrderBy(x => x, new ListComparer());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...