Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of rectangles

I want to put a list of words in order of how they appeared on the page they were found. (Including multiple lines if that is the case)

the quick brown
fox jumped

I have a list of custom Word objects that contain the text of the word, and it's left, right, top, and bottom values with (0, 0) being the top left corner of the page.

words.Add(new Word() { text = "the", box = new rectangle() { left = 10, right = 30, top = 10, bottom = 21 } );
words.Add(new Word() { text = "brown", box = new rectangle() { left = 65, right = 95, top = 11, bottom = 20 } );
words.Add(new Word() { text = "jumped", box = new rectangle() { left = 36, right = 64, top = 26, bottom = 38 } );
words.Add(new Word() { text = "quick", box = new rectangle() { left = 35, right = 60, top = 11, bottom = 24 } );
words.Add(new Word() { text = "fox", box = new rectangle() { left = 10, right = 30, top = 25, bottom = 35 } );

internal class Word
{
    internal Rectangle box { get; set; }
    internal string text { get; set; }
}

I can easily sort a single line by ordering by the left bound, but 2 lines is hurting my brain.

like image 846
Milne Avatar asked Dec 21 '25 12:12

Milne


1 Answers

Use OrderBy and then ThenBy in LINQ, which will order it by the X position, and then sort it by the Y position.

List<Word> sortedWords = words.OrderBy(w => w.box.Left).ThenBy(w => w.box.Top).ToList();
like image 190
Cyral Avatar answered Dec 23 '25 04:12

Cyral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!