Reputation: 5600
I got a list of objects(ip, domainname). and want to find the duplicates in them and remove the ones that has not got www in front of the domainname.
So if it is in the list
192.168.0.0 www.stackoverflow.com
192.168.0.1 stackoverflow.com
I want to remove stackoverflow.com.
So far this is my code I am passing my list of objects to this function:
static List<ServerBindings> removeDuplicates(List<ServerBindings> inputList)
{
Dictionary<string, string> uniqueStore = new Dictionary<string, string>();
List<ServerBindings> finalList = new List<ServerBindings>();
foreach (var currValue in inputList)
{
if (!uniqueStore.ContainsKey(currValue.DomainName))
{
uniqueStore.Add(currValue.DomainName, currValue.IPAddress);
finalList.Add(new ServerBindings { DomainName = uniqueStore.Keys.ToString(), IPAddress = uniqueStore.Values.ToString() });
}
}
return finalList;
}
I have tried linq but as I'm new to it I tried to groupby
but don't know how to say "select ones where it has www in front of domain name".
EDIT:
Tested this again and seems not to work...I mean the linq query selects only the ones that have www in front and ignores the ones without....to clarify if in list we have www.test.com, test.com and test3.com the end result should be www.test.com and test3.com
Upvotes: 1
Views: 542
Reputation: 51369
Something like this should do the whole thing:
serverBindings
.Select(sb => new { Normalized = sb.DomainName.StartsWith("www.") ? sb.DomainName.Substring(4) : sb.DomainName, HasLeadingWWW = sb.DomainName.StartsWith("www."), Binding = sb })
.GroupBy(sbn => sbn.Normalized)
.Select(g => g.OrderBy(sbn => sbn.HasLeadingWWW).First.Binding);
NOTE: I haven't tested it, might need some tweaking.
Upvotes: 0
Reputation: 18474
var result=inputList.Where(x=>x.DomainName.StartsWith("www.")).Distinct();
if distinct doesn't do the job because the bindings are different objects you could do
var result=from x in list
where x.DomainName.StartsWith("www.")
group x by x.DomainName into domain
select new ServerBindings {
DomainName=domain.Key,
IPAddress=domain.Select (d =>d.IPAddress ).First ()
};
Upvotes: 2
Reputation: 7591
return inputList
.GroupBy(key=>key.IpAddress)
.Select(group => {
var domain = group.Any(g=>g.StartsWith("http://www"))
? group.First(g=>g.StartsWith("http://www"))
: group.First();
return new ServerBindings
{
DomainName = group.First
IpAddress = group.Key
};)
.ToList();
Upvotes: -1