0

Hi,

Want to remove duplicates from a list so if my list contains:

www.test.com
test.com
mytest.com

I want the final list to look like below(only selecting the domains with www from the duplicate in front) :

www.test.com
mytest.com

I have this linq but it seems to ignore all the domains which dont have www in front because it is selecting only www ones:

var result=inputList.Where(x=>x.DomainName.StartsWith("www.")).Distinct();

help would be appreciated

2
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by sam1
0

You could do it this way, but this makes some assumptions:

using System;
using System.Collections.Generic;
using System.Linq;

namespace DW_406156_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         List<string> lst_strInput = new List<string>()
         {
            "www.test.com", "test.com", "mytest.com"
         };

         lst_strInput
            .Select(s => s.Replace("www.", ""))
            .Distinct()
            .ToList()
            .ForEach(s => Console.WriteLine(s));
      }
   }
}

Will you ever need to distinguish between fred.wordpress.com and joe.wordpress.com?
...AND are you dealing with URIs or strings?

Edited by thines01: clarity

0

OK. Then that will work.
Just for grins, here is the Uri version which assumes EITHER the host with the www or without the www will work as long as both don't appear:

using System;
using System.Collections.Generic;
using System.Linq;

namespace DW_406156_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         List<Uri> lst_uriInput = new List<Uri>()
         {
            new Uri("http://www.test.com"),
            new Uri("http://test.com"),
            new Uri("http://mytest.com")
         };

         List<Uri> lst_uriFiltered =
            lst_uriInput.ToLookup(k => k.Host.Replace("www.", ""), v => v)
            .Select(kvp => kvp.First())
            .ToList();

         lst_uriFiltered.ForEach(uri => Console.WriteLine(uri.Host));
      }
   }
}

Edited by thines01: clarity

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.