开发者

How to transform this foreach to Linq?

int j = 0;  
foreach (var e in XmlData.Elements())  
{  开发者_StackOverflow
   xDictionary.Add(j++, e.Value);  
}  


You probably shouldn't be using a dictionary if the key is simply the positional index. I'd suggest using a list instead:

var xList = XmlData.Elements().ToList();


Well, this would do it, using the overload of Select which provides the index, and ToDictionary:

var dictionary = XmlData.Elements()
                        .Select((value, index) => new { value, index })
                        .ToDictionary(x => x.index, x => x.value);

That's assuming xDictionary was empty before you started.


Something like this: To create a new dictionary:

var dict = XmlData.Elements()
        .Select((e, i) => new {Element = e, Index = i})
        .ToDictionary(p => p.Index, p => p.Element.Value);

Also if you want to add to an existing dictionary you can use an AddRange convenience extension method:

xDictionary.AddRange(XmlData.Elements()
                    .Select((e, i) => new KeyValuePair<int, string>(i, e.Value)));

And the extension method implementation:

    public static void AddRange<T>(this ICollection<T> source, IEnumerable<T> elements)
    {
        foreach (T element in elements)
        {
            source.Add(element);
        }
    }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜