3
 List<string> ls = new List<string>();
 Feed<Contact> f = cr.GetContacts();

        foreach (Contact e in f.Entries)
            foreach (EMail el in e.Emails)
                if (!(ls.Contains(el.Address.Substring(el.Address.LastIndexOf('@')+1))))
                    ls.Add(el.Address.Substring(el.Address.LastIndexOf('@')+1));

In above code, i am trying to get distinct domain of email id, but i am getting them all whats problem with my logic?

test data:

inp:

abca@gmail.com
sdafdf@yahoo.com
sdfs@gmail.com
ssdf@gmail.com
sdfsf@someOtherDomain.com

... such 20,000 entries

i need to get DISTINCT domains

but my o/p is

gmail.com
yahoo.com
gmail.com
gmail.com
someOtherDomain.com

actually it should be:

gmail.com yahoo.com someOtherDomain.com

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pratik
  • 11,534
  • 22
  • 69
  • 99

1 Answers1

1

It's not obvious what's actually wrong here, but it's an inefficient and ugly way of doing it. I suggest you try this:

var domains = (from contact in cr.GetContacts().Entries
               from email in contact.Emails
               let address = email.Address
               select address.Substring(address.LastIndexOf('@') + 1))
              .Distinct(StringComparer.OrdinalIgnoreCase)
              .ToList();

Having said that, your original code really should have worked. Could you provide some test data which is failing?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Domains are case-insensitive, this is case sensitive. Unless your EMail class already canonicalizes that. And perhaps check if EMail has a property for the domain part. For example `MailAddress` has a `Host` property doing this. (And no I'm not the downvoter) – CodesInChaos Nov 24 '10 at 14:10
  • @CodeInChaos: Edited to make it case-insensitive - although given the input data, I don't think that's what's wrong. – Jon Skeet Nov 24 '10 at 14:15