【问题标题】:Sort list of rectangles矩形的排序列表
【发布时间】:2014-06-11 18:36:44
【问题描述】:

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

the quick brown
fox jumped

我有一个自定义 Word 对象列表,其中包含单词的文本,它是左、右、上和下值,其中 (0, 0) 是页面的左上角。

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 行正在伤害我的大脑。

【问题讨论】:

  • ps。我知道我的“矩形”的宽度和高度格式不正确。为了便于理解,我对其进行了简化。

标签: c# algorithm sorting rectangles


【解决方案1】:

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

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

【讨论】:

  • 看起来不错。我从未使用过“ThenBy”功能。我现在就试试看。
  • 它类似于OrderBy,但是OrderBy 重新排序整个序列,而ThenBy 仅根据给定属性重新排序(例如:它按Y 为所有值排序具有相同的X)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-21
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2014-08-12
  • 1970-01-01
相关资源
最近更新 更多