views:

23

answers:

2

I wrote a method that sorts values of a ComboBox and then saves them into Xml file.

I'm very unhappy how it looks. Please feel free to take it apart and help me optimize it.

The method looks very similar to this one:

public void Save(ComboBox comboBoxItems)
{
    var xmlElements = new XElement("Root");
    List<string> children = new List<string> {comboBoxItems.Text};
    foreach (string child in comboBoxItems.Items)
        if (!children.Contains(child))
            children.Add(child);

    children.Sort();

    foreach (var child in children)
        xmlElements.Add(new XElement("Child", child));

    xmlElements.Save("Output.xml");
}
+1  A: 

Yours isn't that bad. This version is a little kinder to the eyes

// you might need comboBoxItems.Items.OfType<string>()
// doing this by memory lol    
var children = from x in comboBoxItems.Items
                orderby x
                select new XElement("Child", child);
var xmlElements = new XElement("Root", children.ToArray());
xmlElements.Save("output.xml");

This will NEVER become a performance bottleneck (exactly how many items do you have in the combobox), therefore I'd not worry about "performance" unless it specifically crops up as a bottleneck.

Will
It looks like I cannot use LINQ on comboBoxItems.Items. Can I do linq on ComboBox.ObjectCollection?
Vadim
+2  A: 

How about:

public static void Save(ComboBox items) {
  XElement xmlElements = new XElement("Root");
  xmlElements.Add(
    items.Items
      .Cast<string>()
      .OrderBy(s => s)
      .Select(s => new XElement("Child", s))
      .ToArray()
  );
  xmlElements.Save("Output.xml");
}
Guffa
Thanks. It works just fine except that it allows duplicate records to be saved. I tried to use Distinct() but it didn't help.
Vadim
@Vadim: You have to put the Distinct call after the Cast, otherwise it will be comparing them as object references instead of strings.
Guffa