Question

I am trying to get the correct syntax for my LINQ statement. I have a dictionary, and then a method that checks values in that dictionary. I am trying to count the messages to list where the values are not null or empty (they can be manipulated elsewhere)

    ScannerMessages = new Dictionary<string, string>();
    public enum ScanType { GoodScan, Reprint, BadScan, DiscernScanType}
    public ScanType equalMessages()
    {
        lock (lckObj)
        {
            int x = ScannerMessages.Values.ToList().Distinct().Count();
            int y = ScannerMessages.Values.ToList().Count;

            if (ScannerMessages.Values.All(s => string.IsNullOrEmpty(s))) return ScanType.BadScan;
            else if (_ScannerCount == 1) return ScanType.DiscernScanType;
            else if (x < y) return ScanType.GoodScan;
            else if (ScannerMessages.Values.ToList().Distinct().Where(x => x.Value != string.IsNullOrEmpty()).Count() == 1) return ScanType.Reprint;
            else return ScanType.BadScan;
        }
    }

it's this statement that is off

    ScannerMessages.Values.ToList().Distinct().Where(x => x.Value != string.IsNullOrEmpty()).Count()

and I also tried on the list creation on both sides of the ToList() (but they're wrong too)

ScannerMessages.Values.Where(x => x.Value != string.IsNullOrEmpty()).ToList().Distinct().Count()
ScannerMessages.Values.ToList().Where(x => x.Value != string.IsNullOrEmpty()).Distinct().Count()
Était-ce utile?

La solution

 ScannerMessages.Values.Distinct().Count(v => !String.IsNullOrEmpty(v))
  1. You already selected values, thus you already have sequence of strings, and you don't need to try getting value from string with x.Value
  2. You should pass string to String.IsNulllOrEmpty method to verify if this string is null or empty
  3. You don't need to create list with value from dictionary - ValueCollection implements IEnumerable<string> thus you can use Linq methods directly (e.g. Distinct or Where)
  4. If you want to count items in sequence which match some condition (i.e. predicate) then instead of usage Where(predicate).Count() you can use shortcut - overloaded Count(predicate) method which takes predicate.

Autres conseils

Haven't tested but this part looks wrong:

x.Value != string.IsNullOrEmpty()

You are comparing the value of the item to the return value of the boolean function. You should be either testing the return value:

string.IsNullOrEmpty(x.Value)

or checking if the string is equal to something or other

x.Value != ""

or

x.Value != null

or some combination of the two.

There is no Value property on string.Values property gives you a ValueCollection not a collection of KeyValuePairs. You just need:

ScannerMessages.Values.Distinct().Count(x => !string.IsNullOrEmpty(x));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top