简体   繁体   中英

How do you convert IEnumerable<int> to an Int32

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 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 have a List<Int32> , you theoretically have more than one. You can use First() , Last() , or Single() to pull a single element off of that list. They all have OrDefault() versions which will return a 0 if the list is empty - otherwise they will error.

Can't you use the Single or First methods to isolate a single Int32? IEnumerable is implicitly many, when you need one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM