0

I have an string array and a list of string. For example,

string[] stringArray = {"car", "bike", "truck"};
List<string> stringList = new List<string>{"car_blue", "car_red", "truck_yellow", "ship_black", "rocket_orange"};

From the array and list, I want to compare stringArray with stringList and retrieve items that are in the stringArray and is also part of the stringList. Eg: the items retrieved should be, 'car_blue', 'car_red' and 'truck_yellow'?

7
  • 1
    what have you tried? where is your code? Commented Apr 23, 2018 at 9:25
  • i've tried "stringList.Intersect(stringArray);", but it found no matches. Commented Apr 23, 2018 at 9:28
  • Well, "car" is not "car_blue". "car_blue" is "car_blue". Commented Apr 23, 2018 at 9:33
  • 1
    is it necessory that strings in list will always have '_', and first part of string should be matched with strings in array ? Commented Apr 23, 2018 at 9:38
  • 2
    @LittleFlyingTurtle if ' _ ' will not be there in your strings of List, you should edit your question with this clarification. and also comment on the answer regarding the same.. I guess answer of Lucifer will help you in all cases (with and without " _ ") Commented Apr 23, 2018 at 10:00

3 Answers 3

3

You could use LINQ' Where to filter the stringList using the parts before the _:

var result = stringList.Where(x => stringArray.Contains(x.Split('_')[0]));
Sign up to request clarification or add additional context in comments.

2 Comments

i would add .ToList(); to better evelute the result
x.Split('_')[1] is also important.
3

You have to Split by _ to get all tokens, then you can use Intersect...Any:

var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_')).Any());

If you want to ignore the case, so also accept Car_Yellow:

var itemsInBoth = stringList.Where(s => stringArray.Intersect(s.Split('_'), StringComparer.OrdinalIgnoreCase).Any());

Comments

2

The Best way where you don't have to use split is

string[] oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToArray();

or if you want list

List<string> oneMinEnabledTime = stringList.Where(x => stringArray.Any(ele => x.ToLower().Contains(ele.ToLower()))).ToList();

enter image description here

2 Comments

i've tried your way but I still not able to retrieve the list of items i wanted. However, the items inside my list look something like this: 'land\\car_blue', 'sea\\ship_black'... I cant figure out what is wrong with the method.
what is the issue you are facing?

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.