Search code examples
c#listexcept

Compare 2 string List by the first word up to a control character


Is it possible to compare 2 string List by the first word up to a control character ?

Say the string is -

"yellow/tall/wide/white"

Is there away of using -

newList = listOne.Except( listTwo ).ToList();

But only comparing up to the first '/'

Thanks.


Solution

  • A very simple way is the following:

    var result = list1.Where(str1 => !list2.Any(str2 => str2.Split('/')[0] == str1.Split('/')[0]));
    

    Alternatively, you could use Except, but that would require you to create a custom IEqualityComparer:

    public class CustomStringComparer : IEqualityComparer<string>
    {
        public bool Equals(string x, string y)
        {
            // Ensure that neither string is null
            if (!object.ReferenceEquals(x, null) && !object.ReferenceEquals(y, null))
            {
                var x_split = x.Split('/');
                var y_split = y.Split('/');
    
                // Compare only first element of split strings
                return x_split[0] == y_split[0];
            }
    
            return false;
        }
    
        public int GetHashCode(string str)
        {
            // Ensure string is not null
            if (!object.ReferenceEquals(str, null))
            {
                // Return hash code of first element in split string
                return str.Split('/')[0].GetHashCode();
            }
    
            // Return 0 if null
            return 0;
        }
    }
    
    var result = list1.Except(list2, new CustomStringComparer());