开发者

Injecting Code Into Linq

I want to transform foreach to Linq

foreach (var e in  x.Root.Element("Body").Elements())
{
   Block b = new Block();
   b.Text = e.Element("Text").Value;
   b.RadioButtons = e.Element("RadioButtons").Elements().Se开发者_JS百科lect(j => j.Value.ToString()).ToList();
   m.BlockList.Add(b);
}

Can I place some code into Linq query?


Why? This is code is very readable and has side effects. It should remain as a foreach loop.


I'm not sure if this is exactly what you're looking for, but this should work:

var bodyElements = x.Root.Element("Body").Elements()).Select(e => new Block
        {
            Text = e.Element("Text").Value,
            RadioButtons = e.Element("RadioButtons").Elements().Select(j => j.Value.ToString()).ToList()
        }).ToList();

        m.BlockList.AddRange(bodyElements);

Hope this helps!


One way to do that is to project a new Block object in your LINQ query:

m.BlockList = (
    from e in x.Root.Element("Body").Elements()
    select new Block {
        Text = e.Element("Text").Value,
        RadioButtons = (
            from j in e.Element("RadioButtons").Elements()
            select j.Value.ToString()
        ).ToList(),
    }
).ToList();

If m.BlockList already contains items and you want to preserve them, if it supports AddRange() you can do:

m.BlockList.AddRange(
    from e in x.Root.Element("Body").Elements()
    select new Block {
        Text = e.Element("Text").Value,
        RadioButtons = (
            from j in e.Element("RadioButtons").Elements()
            select j.Value.ToString()
        ).ToList(),
    });

The others are right, though: your code is probably fine as it is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜