gpt4 book ai didi

c# - 如何将 2 层深的 foreach 循环转换为 LINQ 表达式以生成 Dictionary>?

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:45 26 4
gpt4 key购买 nike

如何转换这个函数:

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

最佳答案

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

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

关于c# - 如何将 2 层深的 foreach 循环转换为 LINQ 表达式以生成 Dictionary<string,SomeList<Item>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15004152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com