#StackBounty: #c# #foreach #hashset #xelement Improve on my way of selecting multiple XElements with unique values to build list

Bounty: 50

Is there a way to improve upon this? I feel like I have way to many loops going on.

The code builds a string with domain names in it from an XML document. Depending on whether the domain name in the XML doc is in the hostSW (host Starts With), hostCN (host Contains) or hostEW (host EndsWith) element depends on whether I need to append a * to the end, beginning+end, or beginning of the value respectively.

I used a Hashset as a way of making sure that there is no duplication.

var startWith = xdoc.Root
    .Descendants("Test")
    .Elements("hostSW")
    .ToList();
var contains = xdoc.Root
    .Descendants("Test")
    .Elements("hostCN")
    .ToList();
var endsWith = xdoc.Root
    .Descendants("Test")
    .Elements("hostEW")
    .ToList();

HashSet<string> domains = new HashSet<string>(); //use hashset so we don't duplicate results

foreach (XElement test in startWith)
{
    domains.Add(test.Value.ToString() + "*");
}
foreach (XElement test in contains)
{
    domains.Add("*" + test.Value.ToString() + "*");
}
foreach (XElement test in endsWith)
{
    domains.Add("*" + test.Value.ToString());
}

string out = "BEGIN FILE ";
foreach (string domain in domains.ToArray())
{
    out += "BEGIN DOMAIN ";
    out += domain;
    out += " END DOMAIN";
}
out += " END FILE;

return out;


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.