gpt4 book ai didi

c# - 如何使用键将列表转换为字典但不包括键作为元素

转载 作者:行者123 更新时间:2023-11-30 21:34:23 25 4
gpt4 key购买 nike

我有以下 linq 查询,它工作正常:

var jsonString = JsonConvert.SerializeObject(this.DocumentTypes.Select(c => new
{
RowId = c.RowId,
Id = c.Id,
IsDocumentType = c.IsDocumentType
}).ToDictionary(x => x.RowId));

如您所见,我将字典的键设置为 RowId,但只有将 RowId 作为返回的元素包含在内时,我才能使它起作用。

有没有办法在不必将 RowId 作为返回元素包含在内的情况下实现相同的结果?

谢谢。

最佳答案

ToDictionary 过载允许您指定如何构造值的方法。例如,您可能想要这样的东西(注意这也消除了对 Select 的需要):

var data = this.DocumentTypes
.ToDictionary(
dt => dt.RowId,
dt => new { dt.Id, dt.IsDocumentType })); //<< Here we are creating a new anonymous
// type to use as the value

var jsonString = JsonConvert.SerializeObject(data);

关于c# - 如何使用键将列表转换为字典但不包括键作为元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50250194/

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