miguelmpn miguelmpn - 4 days ago 5
C# Question

Linq to XML create elements with unique parent

Having this Linq statement to create an XML

new XElement(ns + "SpecialRegisters",
from reg in registers
where reg.IsUpdateRegister
select new XElement(ns + "UpdateRegisters",
new XElement(ns + "RegID",
new XAttribute("ID", registers.IndexOf(reg).ToString().PadLeft(2, '0'))
)
)
)


Is it possible to create a unique UpdateRegisters element with multiple RegID.
If there are no update registers there should not exist any UpdateRegisters element.

Answer

You could do this instead:

var result=new XElement(ns + "SpecialRegisters");
var updateRegister=register.Where(e=>e.IsUpdateRegister);// To not repeat the same query twice
if(updateRegister.Count()>0)
{
 result.Add( new XElement(ns + "UpdateRegisters", 
                          updateRegister.Select((e,i)=> new XElement(ns + "RegID",i));
}

Update

If you want to do it all in the same statement then you could do this:

 var updateRegister=register.Where(e=>e.IsUpdateRegister);// To not repeat the same query twice
 var result=new XElement(ns + "SpecialRegisters", updateRegister.Any()?
                         new XElement(ns + "UpdateRegisters", updateRegister.Select((e,i)=> new XElement(ns + "RegID",i)):null );

My solution based on yours (miguelmpn)

Speed is not important, as I'm saving a simple and small file..

new XElement(ns + "SpecialRegisters", Registers.Registers.Singleton.Any(x => x.IsUpdateRegister) ?
                     new XElement(ns + "UpdateRegisters", Registers.Registers.Singleton.Where(e => e.IsUpdateRegister).Select((e, i)=> new XElement(ns + "RegID", i))) : null)
Comments