joulesm
joulesm

Reputation: 642

number of distinct object types in a list

I am using C#, Silverlight, Visual Studio for Windows Phone 7.

I currently have a List that contains the generic UIElement, and I can put things like TextBlock or Grid or StackPanel into the List.

For example:

List<UIElement> UIList= new List<UIelement>();
UIList.Add(someUIObject as UIElement);

My question is, is there an efficient way to count the number of object types in my list? For example, if there are 8 TextBlocks and 4 Grids, I would like to know that there are 2 object types in the List. Or if there is 1 TextBlock, 1 Grid, and 1 StackPanel, I would like to know that there are 3 types of objects.

I'm looking for something that is better than O(n^2) performance. My current solution compares each element type to the rest of the element types in the List, something similar to BubbleSort.

Upvotes: 3

Views: 2974

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460138

I understand your question in the following way: you want to count each type in the collection.

Then you can use LINQs GroupBy and for example a Dictionary<String, Int32>, where the key is the name of the type and the value is the number of occurences of that type in the list:

Dictionary<String, Int32> typeCounts = UIList
    .GroupBy(c => c.GetType().FullName)
    .ToDictionary(g => g.Key, g => g.Count());

If you instead just want to know how many different types are in the list, you could simply use above dictionary's Count property or:

int diffTypeCount = UIList.GroupBy(c => c.GetType().FullName).Count();

or if you are interested in a short and efficient approach, you might want to use the ConcurrentDictionary with it's AddOrUpdate method:

var typeCounts = new System.Collections.Concurrent.ConcurrentDictionary<String, Int32>();
foreach (var c in UIList)
{
    typeCounts.AddOrUpdate(c.GetType().FullName, 1, (typeName, count) => count + 1); 
}
int diffTypeCount = typeCounts.Count;

Upvotes: 0

svick
svick

Reputation: 244827

To get the number of different types in the collection, I would use LINQ to first select the type of each object, then took only distinct types and counted those:

int numberOfTypes = UIList.Select(x => x.GetType()).Distinct().Count();

All of this will be O(n), because Distinct() uses a hash table.

Upvotes: 5

L.B
L.B

Reputation: 116138

var types = UIList.GroupBy(ui => ui.GetType())
        .Select(g => new { Type = g.Key, Count = g.Count() })
        .ToList();

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176906

try out

var loader = loaders.OfType<Elementtype>().Count(); 

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038870

The best you could get is O(n) complexity by looping through the elements of the list. You could also use LINQ:

int numberOfTextBoxes = UIList.OfType<TextBox>().Count();

Upvotes: 2

Related Questions