0

I am using the query below to grab all records that have a SubCategoryName == subCatName and i want to return all of there ProductID's as a list of ints. Problem is when my code runs it is only returning 1 int(record) instead of all. How can i make it return all of the records that have that subCatName? Its returning a count = 1 with a capacity of 4. So it is a int[4] but only the first [0] is = to a actual product ID the rest returning zero?

   public List<int> GetPRodSubCats(string subCatName)
    {
        var _db = new ProductContext();

        if (subCatName != null)
        {
            var  query = _db.ProductSubCat
                            .Where(x => x.SubCategory.SubCategoryName == subCatName)
                            .Select(p => p.ProductID);

            return query.ToList<int>();
        }
        return null;
    }
jackncoke
  • 2,000
  • 6
  • 25
  • 66

2 Answers2

2

This seems more like an expected behavior here. How do you know you don't only have 1 record that satisfies the Where predicate.

Your code is correct, however you might want to normalize your comparison.

x => x.SubCategory.SubCategoryName == subCatName

to use a specific case for instance:

x => x.SubCategory.SubCategoryName.ToLower() == subCatName.ToLower()

you might also consider a Trim.

Stan R.
  • 15,757
  • 4
  • 50
  • 58
2

As Daniel already has mentioned, the code should work. But maybe you are expecting that it's case-insensitive or ignores white-spaces. So this is more tolerant:

subCatName = subCatName.Trim();
List<int> productIDs = _db.ProductSubCat
     .Where(x => String.Equals(x.SubCategory.SubCategoryName.Trim(), subCatName, StringComparison.OrdinalIgnoreCase))
     .Select(p => p.ProductID)
     .ToList();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • The class name "Context" and the variable name "_db" indicates that he is using Entity Framework. In this case your code won't work because it can't be translated to an SQL statement. – JustAnotherUserYouMayKnow Mar 01 '13 at 16:33
  • @JustAnotherUserYouMayKnow: Overlooked it somehow. `String.Equals` on the other hand should work as this answer suggests: http://stackoverflow.com/a/841342/284240 – Tim Schmelter Mar 01 '13 at 16:39
  • This will result in an ArgumentException "Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'" when enumerating the query. Stans answer works, also when you add an ".Trim()" before or after the ".ToLower()". This was tested with EntityFramework 4. The stackoverflow answer you linked refers to linq-to-sql, not linq-to-entities. It all depends on what framework he is actually using. ;-) – JustAnotherUserYouMayKnow Mar 01 '13 at 16:54