Check if list of string contains exact part of string

I have a List of strings as follows,

 List<string> str = new List<string>() { "7, 31", "2, 4", "5, 6" };

My input will be something like "1, 2" or "1"

Is there a way to compare if any item in the list of strings excatly matches with the input. In the above case it should return a false. But if my input was "31" it should give me a true or if my input was "7, 31", also it should give true.

I try this code but it always returns true. Please help.

        bool res = false;
        List<string> substrings = new List<string>() { "7, 31", "2, 4", "5, 6" };
        string input = "1"; //Because my input can be "1" or "1, 31" etc spltting it.

        var inputSplitted = input.Split(',');

        var plates = substrings.Select(x => x.Split(','));

        foreach (var item in plates)
        {
            if (item.Any() == inputSplitted.Any())
            {
                res = true;
            }
        }

        Console.WriteLine(res);

>Solution :

item and inputSplitted are arrays of string, so Any called on them is just checking if those arrays are not empty (i.e. if there are any strings in them) which always will evaluate to true for provided examples.

If I understand the rule correctly – input should be either present as full string in the original collection or as part of split by comma original collection – you should compare strings in the collections. Quick fix would be using SequenceEqual with extra handling of one element inputs (also it seems that you need to call .Select(s => s.Trim()).ToArray() on both split results):

if (item.SequenceEqual(inputSplitted)
    || (inputSplitted.Length == 1 && item.Contains(inputSplitted.First())))
{
    res = true;
}

But in general it will result in poor performance if such searches will be performed multiple times. I would recommend using HashSet for such searching:

var hash = substrings
    .SelectMany(s => s.Split(",").Select(s => s.Trim())) // flatten split strings
    .Concat(substrings) // and concatenate with original
    .ToHashSet();

var res = hash.Contains(input); // search in collection (should be prepared one time)

If order of items is not important (i.e. "7, 31" and "31, 7" are the same) you can rebuild search and input strings by splitting them and using OrderBy(s => s) on the split results before concatenating back.

Leave a Reply