views:

266

answers:

2

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

how can I get distinct no from above where first 6 charatcer must be distinct result would be

abcdefXXX872358

6T1XXXXXXXXXXXX11

7AbcdeHA30XXX541

I try something like this

var dist = (from c in arr select c).Select(a => a.Substring(0, 5)).Distinct(); which gives me first 5 character but I want whole string

+5  A: 

Group on the first characters, and get the first string in each group:

IEnumerable<string> firstInGroup =
   arr
   .GroupBy(s => s.Substring(0, 6))
   .Select(g => g.First());
Guffa
Substring should be s.Substring(0, 5) may be typo mistake
NETQuestion
@lincs: The second parameter is the length, and you said that the first six characters should be distinct.
Guffa
A: 

I think the best method would be to implement an IEqualityComparer, as is hinted by the overload on List.Distinct()

    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();
    }
Gregory