C # for Loop with LIST using LINQ

I use LINQ and return the list to my business logic level. I want to change one of the values ​​in the list (change the star rating to an image with the number of stars).

Although counter (i) is working, the FOR loop is not working properly. The first time through it, it stops at the correct IF, but then it pops up in the ELSE statement for everything, and all values ​​end with "star0.png". I don’t seem to be rolling through the list through ??? Thanks in advance!

for (int i = 0; i < ReviewList.Count; i++) { string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC; if (serviceCode == "*") { ReviewList[i].SERVICE.SERVICE_DESC = "star1.png"; } else if (serviceCode == "**") { ReviewList[i].SERVICE.SERVICE_DESC = "star2.png"; } else if (serviceCode == "***") { ReviewList[i].SERVICE.SERVICE_DESC = "star3.png"; } else if (serviceCode == "****") { ReviewList[i].SERVICE.SERVICE_DESC = "star4.png"; } else { ReviewList[i].SERVICE.SERVICE_DESC = "star0.png"; } } 
+4
source share
4 answers

I don’t think the problem with for loop works correctly ... your syntax is good, and iteration # of ReviewList.Count will be written # times.

First, I will ReviewList and ReviewList contents of the ReviewList .

Let me know what you find

+2
source

If all values end with star0.png , then you go through this list. The fact that the else is the only code executed for each element indicates a logical error - perhaps you wanted to do something like this?

 string serviceCode = ReviewList[i].SERVICE.SERVICE_CODE; 
+3
source

If you know that each element will consist of several stars, why not do it ?:

 for (int i = 0; i < ReviewList.Count; i++) { string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC; ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png"; } 
+1
source

Double jump protection with else clause

 for (int i = 0; i < ReviewList.Count; i++) { string serviceCode = ReviewList[i].SERVICE.SERVICE_DESC; if(!serviceCode.Contains(".png")) { // once name set should not be modified if(serviceCode.Contains("*")) ReviewList[i].SERVICE.SERVICE_DESC = "star" + serviceCode.Length + ".png"; else ReviewList[i].SERVICE.SERVICE_DESC = "star0.png"; } } 

LINQ alternative approach

  ReviewList.ForEach(rs=>if(!rs.SERVICE.SERVICE_DESC.Contains(".png")) { rs.SERVICE.SERVICE_DESC = "star" + rs.SERVICE.SERVICE_DESC.Length + ".png"}); 
0
source

All Articles