Home > Back-end >  How can I access string values in Results View where the number of results may vary?
How can I access string values in Results View where the number of results may vary?

Time:09-29

How can I access the string values in IEnumerable Results View, where the results may vary?

Results View

I am using a foreach loop to iterate through a list, and then grabbing the distinct values of VehicleID:

foreach (var trip in paidTrips) {
    var vehicleids = trip
        .Select(x => x.VehicleID)
        .Distinct()
        .ToList();

I know how to do this:

string n = vehicleids[0];
string o = vehicleids[1];

But that gives me an "Index was out of range"-exception if there's more than two items.

I am thinking it would be good to use a for loop to iterate through the indexes and create an array out of them? If so, how could I do that?

CodePudding user response:

The debugger is fooling you. You are looking at a DistinctIterator that was added to a Select query. The values you're seeing in the debugger is the raw data before the DistinctIterator filters it. Since they both have the same value, after Distinct runs, you only have one value in the list, which is why vehicleids[1] fails. So the problem is that your result has less than two items, not more.

You can certainly access list items with an indexer, but the problem in this case is you think you have 2 values but in reality you only have 1. You can also use for or foreach to loop through when you don't know the number of elements (using vehicleids.Count() as the "stop" condition for the for loop.

CodePudding user response:

try this

IEnumerable<string> vehicleIds=paidTrips
        .Select(x => x.VehicleID)
        .Distinct()
        .ToList();
        //or ToArray();

you can acces using foreach loop

foreach( var id in vehicleIds)
{
       Console.WriteLine(id);
}

or just using index

var vehicleId0 = vehicleids[0];
//or 
var vehicleId1=vehicleId[1];

or using linq

var vehicleId=vehicleIds.FirstOrDefault(x=> x=="1223");
  • Related