[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 375
  • Last Modified:

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
0
John Bolter
Asked:
John Bolter
  • 5
  • 5
  • 2
2 Solutions
 
É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
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
É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 SotoCommented:
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
 
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 SotoCommented:
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 5
  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now