0

I have two string lists.

1:

new List<string>{ "jan", "feb", "nov" }

2:

new List<string>{ "these are the months", "this is jan,", "this is feb,", "this is mar,",  "this is jun,", "this is nov"}

I'd like my result to be:

List<string>{ "these are the months", "this is jan,", "this is feb,", "this is nov"}

right now I'm doing a messy split, then a contains linq with a nested foreach.

But there has to be a simpler way, I've thought of a linq left JOIN with list 2 on the left, perhaps, but wouldn't know how to pull it off, if that's even the correct approach.

Any ideas?

Thanks.

A.G.
  • 2,089
  • 3
  • 30
  • 52

1 Answers1

2

You can do this with a little Linq:

var list1 = new List<string>{ "jan", "feb", "nov" };
var list2 = new List<string>{ "these are the months", ... };

var result = list2.Where(x => list1.Any(y => x.Contains(y))).ToList();

However, this result set will not contain the first element, because "these are the months" doesn't contain any of the strings in list1. If this is a requirement you might need to do something like this:

var result = list2.Take(1).Concat(list2.Skip(1).Where(x => list1.Any(y => x.Contains(y)))).ToList();
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Thanks for the quick reply. But, what if there are multiple strings ahead of the "contains", and it's not know now many? Thanks again! – A.G. Nov 14 '13 at 03:51
  • @user1013388 So how do you know which ones need to be included in the result set? – p.s.w.g Nov 14 '13 at 03:53
  • The ones selected in the first way you did it, without the top part then merge that with the original. i thnik that would do it. – A.G. Nov 14 '13 at 03:59
  • @user1013388 But my question is, how do you know how many elements are in the 'top' part if it can vary? If you show the `foreach`-loop you have right now, maybe I'll be able to understand the logic. – p.s.w.g Nov 14 '13 at 04:01
  • yes it can vary. I don't have the code with me. But I think the solution is something along these lines: http://stackoverflow.com/questions/3682437/combining-2-lists-and-and-remove-duplicates-output-in-a-third-list-my-attempts – A.G. Nov 14 '13 at 04:05
  • 1
    @user1013388 Sorry, but that still doesn't help. In any case, if you can determine that there are `n` elements in the 'top' you can use my code and just replace the `1` in my code with `n`. – p.s.w.g Nov 14 '13 at 04:12
  • For the second code segment, it may be simpler to use `var result = list2.Where((x, i) => i == 0 || list1.Any(y => x.Contains(y)))`. – drf Nov 14 '13 at 04:53