0

I i have string of numbers separated by commas ,How to check if another string contained in that string .

For example :

If i have a string :

67,782,452,67632,9,155,323

How to check that 155 is in the previous string using linq ?

2
  • Is LINQ an absolute requirement? Commented Mar 10, 2014 at 10:50
  • @PaoloTedesco No , but i want to know how to do that through linq Commented Mar 10, 2014 at 10:51

4 Answers 4

4

I assume that you want to check if one of the items in the string is your given string. I would split the string first by the delimiter ,, then use Contains or Any:

string[] items = "67,782,452,67632,9,155,323".Split(',');
bool contains = items.Contains("155");
contains = items.Any(i => i == "155");

The problem with the Contains-check on the string is that also "1550" would contain "155".

Sign up to request clarification or add additional context in comments.

4 Comments

is Any give the exact not like Contains ??
i mean u use Contains then Any ?!
@just_name: that's just to demonstrate both ways. Enumerable.Any is more flexible since you could use any code here. Contains must be used with the same type as the array and it used the default equality check. But Conatains is more readable and works also here.
+1 Contains-check on the string is that also "1550" would contain "155"
3

For e.g. using String.Contains or Any (you can use string.Contains in your linq query)

string a = "67,782,452,67632,9,155,323";
var splitted = a.Split(',');
if(splitted.Any(x=> x == "155"))
{
 ...
}

or

if(splitted.Contains("155"))
{
 ...
}

or ugly one-liner

var contains = a.Split(',').Any(x=>x=="155");

2 Comments

This would return true also if the string was for example "1,1550,2"
@PaoloTedesco good point, edited my answer
2

Split the string and then check the resulting array:

string input = "67,782,452,67632,9,155,323";
string[] values = input.Split(',');
bool contained = values.Contains("155");

Comments

2

Using Linq:

var str = "67,782,452,67632,9,155,323";
var arr = str.Split(',');

var isInString = arr.Any(x => x == "155");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.