Get first 6 characters from a string that is different

string[] arr = { "abcdefXXX872358", "abcdef200X8XXX58", "abcdef200X872359", "6T1XXXXXXXXXXXX11", "7AbcdeHA30XXX541", "7AbcdeHA30XXX691" };

      

how can i get great numbers from the top where the first 6 characters should be different the result would be

abcdefXXX872358

6T1XXXXXXXXXXXX11

7AbcdeHA30XXX541

I am trying something like this

var dist = (from c in arr
            select c).Select(a => a.Substring(0, 5)).Distinct();

      

which gives me the first 5 characters, but I want the whole string

+2


source to share


2 answers


Group by first characters and get the first line in each group:



IEnumerable<string> firstInGroup =
   arr
   .GroupBy(s => s.Substring(0, 6))
   .Select(g => g.First());

      

+6


source


I think the best way would be to implement IEqualityComparer as the overload in List.Distinct () hints at



    public class firstXCharsComparer : IEqualityComparer<string>
    {
        private int numChars;
        public firstXCharsComparer(int numChars)
        {
            this.numChars = numChars;
        }

        public bool Equals(string x, string y)
        {
            return x.Substring(0, numChars) == y.Substring(0, numChars);
        }

        public int GetHashCode(string obj)
        {
            return obj.Substring(0, numChars).GetHashCode();
        }
    }
    static void Main(string[] args)
    {
        string[] arr = { "abcdefXXX872358", "abcdef200X8XXX58", "abcdef200X872359", "6T1XXXXXXXXXXXX11", "7AbcdeHA30XXX541", "7AbcdeHA30XXX691" };

        var result = arr.ToList().Distinct(new firstXCharsComparer(6));
        result.Count();
    }

      

0


source







All Articles