user2837480
user2837480

Reputation: 369

Finding comma separated String values in a List<int>

I have a comma separated string variable and i need to check its values exists in a given List

string freeServices = "1,7,13,21";
List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();

i have tried something like this

if (selectedServices.Contains(Convert.Int32(freeServices.Split(','))
{
}

can i do this? or is there any other easy way to find whether the free service ids in selected id list?

Upvotes: 0

Views: 261

Answers (3)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

You could use All and int.Parse;

string freeServices = "1,7,13,21";
List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();
var splittedFreeServices = freeServices.Split(',').Select(k => int.Parse(k));
var result = selectedServices.All(x => splittedFreeServices.Contains(x));
if (result) //booking.SelectedServices contains all elements of freeServices as integer
{

}

Upvotes: 0

programtreasures
programtreasures

Reputation: 4298

Try below query, you willget contains records

var containsValues = booking.SelectedServices.where(e=> freeServices.Split(',').Contains(e.ServiceID));

Upvotes: 0

Backs
Backs

Reputation: 24903

To check, all values are contained in SelectedServices:

string freeServices = "1,7,13,21";
var values = freeServices.Split(',').Select(o=>Convert.ToInt32(o)).ToList();

List<int> selectedServices = booking.SelectedServices.Select(x => x.ServiceID).ToList();

if (selectedServices.All(o=>values.Contains(o))
{
}

Upvotes: 1

Related Questions