I've got a linq query that will return 1 result which will be an integer. I want to assign this to an Int32 variable to be used later, however I get an error that reads, "int does not contain a definition for RatingNumber and no extension method RatingNumber acepting a first argument of type int could be found (are you missing a using directive or an assembly reference?)
this is the code that calls the query
IEnumerable<int> newRatingNumber = getNewRecipeNumbers.newRatingNum();
foreach (var a in newRatingNumber)
{
ratingNumber = a.RatingNum;
}
and this is the query:
public IEnumerable<int> newRatingNum()
{
ratingTableAdapter.Fill(recipeDataSet.Rating);
var newRatingNum = (from a in recipeDataSet.Rating
where a.UserRating == 0 &&
a.FamilyRating == 0 &&
a.HealthRating == 0 &&
a.EaseOfCooking == 0 &&
a.CookingTime == 0
select a.RatingNum);
return newRatingNum;
}
I tried using Convert.ToInt32 to cast the result to an int, this got rid of compiling errors, this however created an InvalidCastException. Anyone have any ideas?
Thanks for the help
Craig
The IEnumerable<T> interface is central to LINQ. All LINQ methods are extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T> .
In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();
The result of the Linq query is not a single Int value, but an IEnumerable. So you need to get a single value out of it, which in your case is the first value:
var newRatingNum = (from a in recipeDataSet.Rating
where a.UserRating == 0 &&
a.FamilyRating == 0 &&
a.HealthRating == 0 &&
a.EaseOfCooking == 0 &&
a.CookingTime == 0
select a.RatingNum).FirstOrDefault();
FirstOrDefault()
will return the first value in the Enumberable, or will return 0 if the Enumberable is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With