如何将2级foreach循环转换为LINQ表达式以生成Dictionary<;字符串,SomeList<;项目&

本文关键字:lt Dictionary 字符串 项目 SomeList foreach 2级 循环 转换 表达式 LINQ | 更新日期: 2023-09-27 18:00:36

如何转换此函数:

void MyFunc () {
    foreach (var k in problems.Keys)
    {
        var list = new ObservableCollection<ListViewItem>();
        listViewItems.Add(k, list);
        foreach (var i in problems[k].Items)
        {
            list.Add(new ListViewItem
            {
                Token = i.Token,
                IsFatalError = i.IsFatal,
                Checked = false,
                Line = i.Token.Position.Line,
                Description = i.Description,
                BackgroundBrush = i.IsFatal ? Brushes.Red : null
            });
        }
    }
}

到LINQ查询语法?以下是类型和变量:

public class ProblemsList {
    public class Problem {
        public IToken Token { get; set; }
        public string Description { get; set; }
        public bool IsFatal { get; set; }
    }
    public List<Problem> Items { get { return problems; } }
}
public class ListViewItem {
    public bool IsFatalError { get; set; }
    public bool Checked { get; set; }
    public int Line { get; set; }
    public string Description { get; set; }
    public Brush BackgroundBrush { get; set; }
}
Dictionary<string, ProblemsList> problems;
Dictionary<string, ObservableCollection<ListViewItem>> listViewItems
    = new Dictionary<string, ObservableCollection<ListViewItem>>();

如何将2级foreach循环转换为LINQ表达式以生成Dictionary<;字符串,SomeList<;项目&

以下是我的操作方法(使用链式方法语法):

listViewItems = problems.ToDictionary(
    p => p.Key,
    p => new ObservableCollection<ListViewItem>(
        p.Value.Items.Select(
            i => new ListViewItem
                {
                    Token = i.Token,
                    IsFatalError = i.IsFatal,
                    Checked = false,
                    Line = i.Token.Position.Line,
                    Description = i.Description,
                    BackgroundBrush = i.IsFatal ? Brushes.Red : null
                }
            )
        )
    );

更新

一个尽可能使用查询语法的版本:

listViewItems = (
        from p in problems
        select new
            {
                Key = p.Key,
                Value = from i in p.Value.Items
                        select new ListViewItem
                                {
                                    Token = i.Token,
                                    IsFatalError = i.IsFatal,
                                    Checked = false,
                                    Line = i.Token.Position.Line,
                                    Description = i.Description,
                                    BackgroundBrush = i.IsFatal 
                                                        ? Brushes.Red 
                                                        : null
                                }
            }
    ).ToDictionary(x => x.Key, x => x.Value);