list<rectangle[]> array grouping
I have an array of rectangle elements. each element in the array can be able to represent several diffrent rectangles in it. i would want to find out how can i group similar list items and show their count. e.g the list contains 10 rectangle arrays. of the 10 there are 4 elements which are similar (i.e 4 rectangle elements with the same number, size, orientation of the rectangles in it) for the example i would love to have an end 开发者_JS百科result which shows a list of 7 alements and the count eg. the 6 single elements and the 7th elements showing a count of 4. c# or vb.net
If you can override Equals
on your rectangle to determine when you consider two rectangles equal, you could do the following Linq query.
List<Rectangle[]> rectangleArr;
var query = (from r in rectangleArr.Cast<Rectangle>()
group r by r into gr
select new { Count = gr.Count(), Value = gr.Key });
foreach (var item in query)
{
Console.WriteLine("Item: {0}, Count: {1}", item.Value, item.Count);
}
If you don't want an anonymous type you could create a class:
class RectangleGroup
{
public Rectangle Value { get; set; }
public int Count { get; set; }
}
then select like this:
select new RectangleGroup() { Count = gr.Count(), Value = gr.Key }
You can use Tuple:
List<Rectangle> l = new List<Rectangle>();
l.Add(new Rectangle(1, 2, 3, 4));
l.Add(new Rectangle(1, 2, 3, 4));
l.Add(new Rectangle(10, 20, 30, 40));
var grouped = l
.GroupBy(item => item)
.Select(group => new Tuple<Rectangle, int>(group.Key, group.Count()));
foreach (var t in grouped)
{
Console.WriteLine("There are {0} rectangles like {1}.", t.Item2, t.Item1);
}
精彩评论