排列矩形列表

时间:2014-04-25 21:31:44

标签: c# algorithm sorting rectangles

我想按照它们在找到的页面上的显示顺序列出一个单词列表。 (如果是这种情况,包括多行)

the quick brown
fox jumped

我有一个自定义Word对象列表,其中包含单词的文本,左侧,右侧,顶部和底部值,页面左上角有(0,0)。 / p>

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; }
}

我可以通过左边界排序轻松排序一行,但是2行伤害了​​我的大脑。

1 个答案:

答案 0 :(得分:4)

LINQ中使用OrderBy然后ThenBy,它将按X位置排序,然后按Y位置排序。

List<Word> sortedWords = words.OrderBy(w => w.box.Left).ThenBy(w => w.box.Top).ToList();