Question

Here is my table data ,

 Areas                           Cities
==============================================================
Area1                   City1 , City2 , City3 , City4
Area2                   City5 , City6 , City7 , City8
Area3                   City9 , City10 , City11 , City12
Area4                   City13 , City14 , City15 , City16

If I give the value City1 , I want to get Area1 .
(eg. City7 => Area2 , City14 => Area4) .
Is there any short way to do it using Lambra Expression ?

Was it helpful?

Solution

Try this code:

yourDataTable.First(x => x.Cities.Split(',').Any(y => y.Trim() == "City1"))

Where search term is string like City 1

OTHER TIPS

if you need exact match, try

var rec = tbl.ToList().FistOrDefault(x => x.Cities.Split(',')
                                  .Any(City => City == SearchTerm));

Contains will give wrong results, since if you search City1 it will match even City11

Note:

since you have space before the , you need to call Trim method to get the word and also if you need do a case intensive search do as below

var rec = tbl.ToList().FistOrDefault(x => x.Cities.Split(',')
                                  .Any(City => City.Trim().Equals(SearchTerm, StringComparison.InvariantCultureIgnoreCase)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top