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

Camel Case property names in json files are not getting mapped to Java Object

json jackson fasterxml

I have a json object with property names like: itemsRequired, sortable_list. And in my ObjectMapper, I have

iPhone MotionShake Stops Working After Clicking Link

iphone objective-c xcode cocoa-touch uiwebview

I have an app that displays a UIWebView after the user shakes the phone. It works perfectly until the user clicks a link in the webview. Once the user clicks a link, they must click white space i...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.