我想根据底部的Y值对用Rectangle表示的文本区域进行分组,然后编写GroupSentces函数并得到无限循环。请帮助我修复此功能。 GroupSentence功能是将文本区域分组以表示一个句子。
public void GroupSentences()
{
groupedsentences = new List<List<Rectangle>>();
List<Rectangle> copysentences = sentences.ToList();
for (int i = 0; i < sentences.Count; i++)
{
List<Rectangle> recs = new List<Rectangle>();
Rectangle rec = sentences.ElementAt(i);
recs.Add(rec);
copysentences.Remove(rec) ;
List<int> foundedindex = new List<int>();
List<Rectangle> foundedrecs = new List<Rectangle>();
for (int j = 0; j < copysentences.Count; j++)
{
Rectangle nextrec = copysentences.ElementAt(j);
if (Math.Abs(rec.Bottom - nextrec.Bottom) <= 2 ||
Math.Abs(nextrec.Bottom - rec.Bottom) <= 2)
{
foundedindex.Add(j);
Rectangle foundedrec = copysentences.ElementAt(j);
foundedrecs.Add(foundedrec);
}
}
foreach (var item in foundedrecs)
{
copysentences.Remove(item);
}
foreach (var item in foundedindex)
{
recs.Add(copysentences.ElementAt(item));
}
groupedsentences.Add(recs);
if (sentences.Count > 0)
{
i = -1;
}
else
return;
}
}
答案 0 :(得分:0)
这是一个很好的例子,首先,我使用二进制排序对复制的列表进行排序(比在2个循环中比较2个元素更快)。接下来,我在列表中循环一次,并在上一项小于下一项时创建一个新组。请享用!
using System;
using System.Collections.Generic;
namespace ee
{
public class Core
{
public static void Main()
{
GroupSorter gs = new GroupSorter();
gs.GroupCorrect();
}
}
public class GroupSorter
{
List<Rectangle> sentences = new List<Rectangle>();
List<List<Rectangle>> groupedsentences = new List<List<Rectangle>>();
public GroupSorter()
{
Random recBottom = new Random();
for (int i = 0; i < 100; i++)
{
sentences.Add(new Rectangle() { Bottom = recBottom.Next(10) });
}
}
public void GroupCorrect()
{
List<Rectangle> copysentences = new List<Rectangle>(sentences);
copysentences.Sort();
List<Rectangle> lastGroup = null;
bool createGroup = true;
foreach (Rectangle r in copysentences)
{
if (lastGroup != null)
{
Rectangle compRec = lastGroup[0]; //Get last group, first element
createGroup = (compRec.CompareTo(r) != 0); //BottomRec not equal so new group
}
if (createGroup)
{
lastGroup = new List<Rectangle>();
groupedsentences.Add(lastGroup);
}
lastGroup.Add(r);
}
}
}
public class Rectangle: IComparable<Rectangle>
{
public Rectangle()
{ }
public int Bottom { get; set; }
public int CompareTo(Rectangle other)
{
return Bottom.CompareTo(other.Bottom);
}
}
}