John
John

Reputation: 3945

convert string to array not working

Im running through a list and extracting the position value from each record

string allPositionsListed = "";
int lastRecord = volunteerAssignmentList.Count;
int currentRecord = 0;
foreach (Volunteer va in volunteerList)
{
  currentRecord++;
  if (currentRecord == lastRecord)
  {
      allPositionsListed += va.Position;
  }
  else
  {
     allPositionsListed += va.Position + ",";
  }
}

//allPositionsListed returns: "51000785,52012986"

I have written a query extracting all the records from the positionTable where position is found.. if I use

var allPositions = new string[] { "51000785", "52012986" };

List<PositionTable> positionList = (from p in DbContext.PositionList
                 where allPositions.Contains(p.Position)
                select p).ToList();

this returns the correct results...but as the allPositions values may be different how do I convert it to the necessary string array. ive tried

var allPositions2 = allPositionsListed.ToArray();

but this returns 
[0]5
[1]1
[2]0
[3]0
[4]7
etc...

when I need 
[0]51000785
[1]52012986

Upvotes: 1

Views: 146

Answers (2)

DavidG
DavidG

Reputation: 119166

Instead of generating a string from your initial data, you can go directly to an enumerable, something like this should work:

var allPositions = volunteerList
    .Select(v => v.Position)
    .ToList();

Which will allow you to now do this:

var positionList = (from p in DbContext.PositionList
                    where allPositions.Contains(p.Position)
                    select p)
    .ToList();

Upvotes: 2

Mohsen Kamrani
Mohsen Kamrani

Reputation: 7457

Simply use the Split method:

var allPositionsListed = "51000785,52012986";
var allPositions2 = allPositionsListed.Split(',');

allPositions2 will be:
allPositions2[0] -> "51000785"
allPositions2[1] -> "52012986"


If you see the KB, it says this about the output of the String#ToArray method

An array that contains the elements from the input sequence.

So, it is working as expected (of course)! and you need to use the right method.

Upvotes: 1

Related Questions