Question

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.

Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top