Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert IEnumerable<int> to an Int32

Tags:

c#

linq

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

like image 252
Craig Smith Avatar asked Oct 23 '12 21:10

Craig Smith


People also ask

What is IEnumerable int in C#?

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> .

Can we convert IEnumerable to List C#?

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();


1 Answers

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.

like image 122
System Down Avatar answered Sep 19 '22 06:09

System Down