2

I have a List of strings that contain partial values, ie

var list = new List<string>{"A/B", "C/D"};

And in my DB I have records such as

  1. A/B/X
  2. X/C/V/B
  3. G/H/J
  4. C/D/D/C
  5. A/C
  6. A/B

So I would like to now query all the items from DB that start with any of values contained in list. From the example 1, 4 and 6 should be returned.

I have other logic that is doing the same thing but other way around, so I can query like .Where(x => list.Contains(x)), but can't figure out how to select values that start with items contained in list using LINQ.

Erki M.
  • 5,022
  • 1
  • 48
  • 74

1 Answers1

3

Assuming you are using EF to get the data from your DB, you can do the following:

var list = new List<string>{"A/B", "C/D"};
var query= context.YourDbSet.Where(e=>list.Any(a=>e.Column.StartWith(a)));// Column is a property of type string.

Anyways the main idea here is check if your items start with one of the elements of list, you can do that using StartWith method of string. If your items collection is a list of strings then do this:

var query= items.Where(e=>list.Any(a=>e.StartWith(a)));
ocuenca
  • 38,548
  • 11
  • 89
  • 102