0

I have one list. I want check if list[i] contains string "6 1". But this code thinks 6 13 24 31 35 contains "6 1". Its false.

6 13 24 31 35
1 2 3 6 1

stringCheck = "6 1";
List<string> list = new List<string>();
list.Add("6 13 24 31 35");
list.Add("1 2 3 6 1");
for (int i=0; i<list.Count; i++)
    {
        if (list[i].Contains(stringCheck)
           {
              // its return me two contains, but in list i have one
           }
    }
brz
  • 5,926
  • 1
  • 18
  • 18
mehelta
  • 89
  • 1
  • 10
  • 4
    You realize that `list.Add("6 13 24 31 35");` just adds one item to the list, right? – Ghasem Oct 11 '14 at 16:52
  • Can you not use a List> ? – vc 74 Oct 11 '14 at 16:53
  • No. Your `list[i].Contains(stringCheck)` returns `true`. What is your _real_ question exactly? – Soner Gönül Oct 11 '14 at 16:53
  • `"6 13 24 31 35"` does contain the substring `"6 1"`. It's true. You highlighted the matching characters in your own question above. Remember that you are dealing with character sequences here, not space-separated numbers. Neither the C# language, nor the Framework Class Library methods, know what a string's contents might *mean* to you; all they see is a sequence of characters. – stakx - no longer contributing Oct 11 '14 at 17:04

1 Answers1

0

But this code thinks 6 13 24 31 35 contains "6 1". Its false. […]

List<string> list = new List<string>();
list.Add("6 13 24 31 35");
list.Add("1 2 3 6 1");

No, it's true because you are dealing with sequences of characters, not sequences of numbers here, so your numbers get treated as characters.

If you really are working with numbers, why not reflect that in the choice of data type chosen for your list?:

// using System.Linq;

var xss = new int[][]
{
    new int[] { 6, 13, 24, 31, 35 },
    new int[] { 1, 2, 3, 6, 1 }
};

foreach (int[] xs in xss)
{
    if (xs.Where((_, i) => i < xs.Length - 1 && xs[i] == 6 && xs[i + 1] == 1).Any())
    {
        // list contains a 6, followed by a 1
    }
}

or if you prefer a more procedural approach:

foreach (int[] xs in xss)
{
    int i = Array.IndexOf(xs, 6);
    if (i >= 0)
    {
        int j = Array.IndexOf(xs, 1, i);
        if (i + 1 == j)
        {
            // list contains a 6, followed by a 1
        }
    }
}

See also:

Community
  • 1
  • 1
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268