CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2008
    Posts
    14

    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

  2. #2
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    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.

  3. #3
    Join Date
    Apr 2010
    Location
    .NET 3.5 / VS2008
    Posts
    7

    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)

  4. #4
    Join Date
    Nov 2008
    Posts
    14

    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
  •  





Click Here to Expand Forum to Full Width

Featured