1

如何转换此功能:

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>>();
4

1 回答 1

5

这是我的做法(使用链式方法语法):

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);
于 2013-02-21T14:11:57.720 回答