locked
LINQ statement not returning what I expect RRS feed

  • Question

  • In my grid view application, the user clicks on the group headers to go to the group detail page.  My app allows the user to edit the properties of the grid view items and sometimes they can switch to other groups.  I'm trying to track down what I think might be a bug in my data source but I'd like to see if there's another way to write my LINQ statement so it's easier to debug.

    // Simple linear search is acceptable for small data sets
    var matches = _sampleDataSource.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));
    if (matches.Count() == 1) return matches.First();
    return null;

    The UniqueId being passed in is "Blue_Sky~95" and you can see that it is located in my ObservableCollection.  Obviously, there's a problem because the code couldn't find the first item so it assumed it wasn't in the collection and created a new group with the same name.  Since I'm not that familiar with expressions like the one above, I was wondering if there's another way to expand the statement so it's easier for me to debug and figure out what's going on.

    _sampleDataSource.AllGroups[0].UniqueId
    "Blue_Sky~95"
    _sampleDataSource.AllGroups[1].UniqueId
    "Blue_Sky~95"
    _sampleDataSource.AllGroups[2].UniqueId
    "Inox~351"
    _sampleDataSource.AllGroups[3].UniqueId
    "Takumi~628"
    _sampleDataSource.AllGroups[4].UniqueId
    "Dreams_Fixed~848"
    
    
    
    
    
    

    Sunday, February 24, 2013 2:06 AM

Answers

  • Your query looks ok.  

    Is the collection list above the state before or after the code snippet was executed?

    If before, then your code will return null because the match.Count() will be 2.  Your code will return a match only if there is a unique match.  If there are duplicates, then it will also return null and create more duplicates somewhere else, I presume.

    • Marked as answer by Lisa19 Sunday, February 24, 2013 3:08 AM
    Sunday, February 24, 2013 2:51 AM

All replies

  • Your query looks ok.  

    Is the collection list above the state before or after the code snippet was executed?

    If before, then your code will return null because the match.Count() will be 2.  Your code will return a match only if there is a unique match.  If there are duplicates, then it will also return null and create more duplicates somewhere else, I presume.

    • Marked as answer by Lisa19 Sunday, February 24, 2013 3:08 AM
    Sunday, February 24, 2013 2:51 AM
  • Good point.  The dump of the collection was taken right before the method returns null.  In the immediate window, matches.Count() returns two as you suggested.  So I'm thinking that I could at least just return the first match.
    Sunday, February 24, 2013 3:08 AM