-
April 26th, 2010, 05:47 AM
#1
Query regarding LinQ to Objects
Hello All,
I seek your help in the following case.
I have a base class say ClassBase and two derived class deriving from ClassBase, say ClassD1 and ClassD2.
I have a collection (List) object which can store objects of type ClassBase
in my code I create several derived class objects(say in 100s) and store in the collection object as said above.
now at any give execution point I need to know how many instance of ClassD1 is stored in the collection object.
I understand that this can be achieved using using writing a query using LinQ to objects, but couldnt work out the exact query, could some one help or educate me on this?? please...
Regards
Radkrish
-
April 26th, 2010, 06:31 AM
#2
Re: Query regarding LinQ to Objects
Code:
list.Count(i => i.GetType() == typeof(ClassD1));
- Make it run.
- Make it right.
- Make it fast.
Don't hesitate to rate my post.
-
April 26th, 2010, 06:37 AM
#3
Re: Query regarding LinQ to Objects
This is the first time I tried LinQ but here is something that worked for me:
Code:
class ClassBase { }
class ClassD1 : ClassBase { }
class ClassD2 : ClassBase { }
Code:
var list = new List<ClassBase> { new ClassD1{} ,
new ClassD1{} ,
new ClassD1{} ,
new ClassD2{} ,
new ClassD1{} ,
new ClassD2{} ,
new ClassD2{} ,
new ClassD1{}};
var Found = from o in list
group o by o.GetType();
foreach (var clsType in Found)
Console.WriteLine(clsType.Key +" "+ clsType.Count());
If you need to get the amounts frequently, you should consider wrap a list with counters for each type (using Dictionary<Type, int> for counters and override add/delete/clear)
-
April 26th, 2010, 07:02 AM
#4
Re: Query regarding LinQ to Objects
Hello boudino and SAAM007,
Thanks a lot and both the solution are working for me.
Regards
RadKrish
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|