1

I have a List<List<string>> and when I try to search with the List<string> it returns no results.

Any ideas?

Thanks

        List<List<string>> test = new List<List<string>>();

        List<string> ff = new List<string>();
        ff.Add("1");
        ff.Add("ABC 1");
        test.Add(ff);

        ff = new List<string>();
        ff.Add("2");
        ff.Add("ABC 2");

        test.Add(ff);

        var result = test.Where(x=>x.Contains("ABC"));

        //result.Count(); is 0
Nate
  • 30,286
  • 23
  • 113
  • 184
Jon
  • 38,814
  • 81
  • 233
  • 382

3 Answers3

13

Neither of your lists contains the element "ABC".

If you want to find the lists that have an element that contains "ABC" as a substring you can do this:

var result = test.Where(x => x.Any(y => y.Contains("ABC")));
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • To make it work, one would have to override the Contains() method of `List` to search within each string and just equal to each string, which could be slow. – Nate Feb 09 '11 at 20:36
  • This works but I dont understand how because Any() just returns a bool – Jon Feb 09 '11 at 20:41
  • The Any is a predicate on the select. It's the same as saying "Select where Y = ABC". You wouldnt expect your select to not work because your where clause deals with booleans. – asawyer Feb 09 '11 at 20:45
  • Thanks. Is it possible to make it case-insensitive? – Jon Feb 09 '11 at 20:50
  • @Jon: See this question for case-insensitive `string.Contains`: http://stackoverflow.com/questions/444798/case-insensitive-containsstring – Mark Byers Feb 09 '11 at 20:52
0

none of your lists contain the string "ABC". It doesn't search the string when you use that contains function, it just matches the whole string. If you want to search for a partial string, then you have to use something like the following:

var result = test.Where(x => x.Where(y => y.Contains("ABC").Count() > 0));
Scott M.
  • 7,313
  • 30
  • 39
0

Its because you are doing a list of a list and not going far enough down in your selection. Something like this should give you two results:

var result = test.Select(x => x.Where(y => y.Contains("ABC")));
Jonathan Bates
  • 1,835
  • 14
  • 22