1

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

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

5 Comments

While your answer is correct, there's no need to even generate the string in the first place.
@DavidG, Yes, but I wanted to point exactly to where the problem is. Definitely the problem could be solved by using just the contains method but he wouldn't realize that he's calling the wrong method for the purpose.
Even your answer would ultimately lead to uing Contains too.
@DavidG, yes, and what's wrong with that. Read the title of the question again please, then decide how the answer should look like.
All I'm saaying is that there was no need to do this at all, it's a waste of resources.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.