LINQ query to Count

Hi, I am learning C# at the moment so my apology for writing two posts here in two days.

Todays problem is LINQ.

I have written the code below. It works. It counts the number of times searchField appears in a lookup.

        private int countKeys(Lookup lookup, String searchField)
        {
            int flookupCount = 0;
            for (int lookupIndex = 0; lookupIndex < lookup.Count; lookupIndex++)
                if (lookup.GetName(lookupIndex) == searchField)
                    flookupCount++;
            return flookupCount;
        }

Open in new window


What I would like is to produce the same count number using LINQ.

I think it should be easy, but the book I am following only has examples of more simple stuff.

This isn't C# I want to use anywhere, it is just C# I want to write to help me understand LINQ better.

I think I am wanting LINQ where the key bit looks something like this

        int counted = from items in lookup
                      group items by items.GetName into temp
                           select new { temp.Count() };

Open in new window


but this doesn't compile.

Can anyone help me with the general syntax here, or confirm whether I can rewrite my C# code that has the for loop in LINQ.

Thank you

John B
John BolterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
can't you just use the Count() extension method:

int counted = lookup.Count();
0
John BolterAuthor Commented:
Hi, thanks Eric, but no I can't as I need to compare lookup.GetName(0) and lookup.GetName(1) and lookup.GetName(2) and so on with the string "searchField". I want a count of the number of times lookup.GetName(n) == "searchField"
Regards
John B
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Éric MoreauSenior .Net ConsultantCommented:
Can you try this:

int counted = from items in lookup
                      group items by items.GetName into temp
                           select new { Count = temp.Count(), temp };
0
John BolterAuthor Commented:
Thank you for persisting with me Eric.

No it doesn't work.

I have provided an example of what "lookup" looks like in C#

        private class Lookup
        {
            public String GetName(int index)
            {
                String returnValue = null;
                switch (index)
                {
                    case 1:
                        returnValue = "A";
                        break;
                    case 2:
                        returnValue = "A";
                        break;
                    case 3:
                        returnValue = "XXX";
                        break;
                    default:
                        returnValue = "YYY";
                        break;
                }
                return returnValue;
            }

            public int Count
            {
                get
                {
                    return 4;
                }
            }
        }


        private int countKeysWITH_LOOP(Lookup lookup, String fieldName)
        {
            int fieldCount = 0;
            for (int numberOfFields = 0; numberOfFields < lookup.Count; numberOfFields++)
                if (lookup.GetName(numberOfFields) == fieldName)
                    fieldCount++;
            return fieldCount;
        }

        //private int countKeysWITH_LINQ(Lookup lookup, String fieldName)
        //{
        //    int fieldCount = from items in lookup
        //                      group items by items.GetName into temp
        //                    select new { Count = temp.Count(), temp };
        //    return fieldCount;
        //}

Open in new window


The bit "countKeysWITH_LINQ" with code sort of like what you suggested just doesn't compile.

Thank you

John B
0
Fernando SotoRetiredCommented:
Hi John;

The way you were constructing your query you should be doing this first query.
int counted = (from items in lookup
               group items by items.GetName into temp
               where temp.Key == searchField
               select temp.Count()).FirstOrDefault();

Open in new window


I would have done it this way because it is simpler and less processing.
              
int counted2 = (from items in lookup
                where items.GetName == searchField
                select items).Count();              

Open in new window

0
Éric MoreauSenior .Net ConsultantCommented:
If  I read correctly, lookup is not a list? LINQ is use to query list!
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
John BolterAuthor Commented:
Thanks for your replies Eric and Fernando.

I just cannot see how to do this.

I attach a whole made up program showing what I want to do. It just won't compile. I am obviously being a bit dim.

using System;
using System.Linq;

namespace ConsoleApplication1
{

    public class Lookup
    {
        public String GetName(int index)
        {
            String returnValue = null;
            switch (index)
            {
                case 1:
                    returnValue = "A";
                    break;
                case 2:
                    returnValue = "A";
                    break;
                case 3:
                    returnValue = "XXX";
                    break;
                default:
                    returnValue = "YYY";
                    break;
            }
            return returnValue;
        }

        public int Count
        {
            get
            {
                return 4;
            }
        }
    }


    class Program
    {




        int CountKeysWITH_LOOP(Lookup lookup, String fieldName)
        {
            int fieldCount = 0;
            for (int numberOfFields = 0; numberOfFields < lookup.Count; numberOfFields++)
                if (lookup.GetName(numberOfFields) == fieldName)
                    fieldCount++;
            return fieldCount;
        }




        int CountKeysWITH_LINQ(Lookup lookup, String fieldName)
        {
            int counted2 = (from items in lookup
                            where items.GetName == searchField
                            select items).Count();
            return counted2;
        }

        static void Main(string[] args)
        {
            Program program = new Program();

            Lookup lookup = new Lookup();

            Console.WriteLine(program.CountKeysWITH_LOOP(lookup, "B"));     //will display 0 on command line
            Console.WriteLine(program.CountKeysWITH_LOOP(lookup, "XXX"));   //will display 1 on command line
            Console.WriteLine(program.CountKeysWITH_LOOP(lookup, "A"));     //will display 2 on command line

            Console.WriteLine(program.CountKeysWITH_LINQ(lookup, "B"));     //will display 0 on command line
            Console.WriteLine(program.CountKeysWITH_LINQ(lookup, "XXX"));   //will display 1 on command line
            Console.WriteLine(program.CountKeysWITH_LINQ(lookup, "A"));     //will display 2 on command line
        }
    }
}

Open in new window

0
Fernando SotoRetiredCommented:
Hi John;

As Eric stated line works on collection of object such as a List<...> but not on a single object.

This line in your code, Lookup lookup = new Lookup();, is a single object of type Lookup. If you had a collection of lookup as the following line

List<Lookup> lookup = new List<Lookup>();

Linq would work with it, but in this case it would not make sense to use a collection of lookup.
0
John BolterAuthor Commented:
Oh right, I missed the comment from Eric above.

I was working on this till just before midnight last night.

Thank you both. I am learning C#, the hard way by myself.
0
Éric MoreauSenior .Net ConsultantCommented:
This code is working but I don't understand what you are trying to achieve with it!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> listOfLookupus = new List<string>();

            Lookup lookup = new Lookup();

            //int fieldCount = 0;
            for (int numberOfFields = 0; numberOfFields < lookup.Count; numberOfFields++)
                listOfLookupus.Add(lookup.GetName(numberOfFields));


            Console.WriteLine(listOfLookupus.Count(i => i == "B"));     //will display 0 on command line
            Console.WriteLine(listOfLookupus.Count(i => i == "XXX"));   //will display 1 on command line
            Console.WriteLine(listOfLookupus.Count(i => i == "A"));     //will display 2 on command line
        }

    }

    public class Lookup
    {
        public String GetName(int index)
        {
            String returnValue = null;
            switch (index)
            {
                case 1:
                    returnValue = "A";
                    break;
                case 2:
                    returnValue = "A";
                    break;
                case 3:
                    returnValue = "XXX";
                    break;
                default:
                    returnValue = "YYY";
                    break;
            }
            return returnValue;
        }

        public int Count
        {
            get
            {
                return 4;
            }
        }
    }

}

Open in new window

0
John BolterAuthor Commented:
Thanks Eric, I am just trying to learn LINQ, and it is hard.
I am starting at University after summer and want to learn this before I start my computer science degree.
Thank you for your replies.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.