Make foreach loop argument more efficent

Quick question, I have written this code (and it works perfectly)

foreach (XElement element in xdoc.Descendants("camera").Where(info => info.Element("group").Value == "A"))
{
    A.Items.Add(AddToGroup(element));
}
foreach (XElement element in xdoc.Descendants("camera").Where(info => info.Element("group").Value == "B"))
{
    B.Items.Add(AddToGroup(element));
}

Is there a way I could make this more efficient? In particular, I am wondering if the foreach loops could be fused together in some way, and/or the argument inside the foreach loop could be made easier somehow...

Answers


foreach (XElement element in xdoc.Descendants("camera"))
{
    var value = element.Element("group").Value;
    if (value == "A")
        A.Items.Add(AddToGroup(element));
    else if (value == "B")
        B.Items.Add(AddToGroup(element));
}

Although I would just use Linq


Yes you can merge the two loops together, you just need the results set to include both sets of data then test correctly inside the foreach loop

foreach (XElement element in xdoc.Descendants("camera")
                                 .Where(info => info.Element("group").Value == "A") || 
                                                info.Element("group").Value == "B"))
{
    if(element.Element("group").Value == "A")
        A.Items.Add(AddToGroup(element));
    else
        B.Items.Add(AddToGroup(element));
}

if you had more elements just use else if statements to chain the tests along.


Need Your Help

Interactive user form in MS Access 2007

sql forms ms-access-2007

I'd like to design user form where there will be 2 buttons (Query1 and Query2), the text box (InputName) and label (Output).

ThreadLocal for multithreaded access to SimpleDateFormat

java thread-safety simpledateformat thread-local

I have a number of Java date patterns and want to reuse them multiple times in SimpleDateFormat objects across different threads, via static references, for speed.