gpt4 book ai didi

c# - Linq 查询创建字符串数组错误列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:04:44 24 4
gpt4 key购买 nike

我正在尝试创建一个字符串数组列表。下面是代码。

public List<string[]> GetRec(int hid)
{
var list =
(from x in table1
join y in table2 on x.Hid equals y.Hid
where x.Hid == hid
select new[] {x.name, x.Description, x.user}).ToList();
return list;
}

但我收到以下错误

"The array type 'System.String[]' cannot be initialized in a query result.
Consider using 'System.Collections.Generic.List`1[System.String]' instead."

谁能告诉我这里出了什么问题。任何帮助将不胜感激。

提前致谢

最佳答案

Can anyone suggest me what is wrong here

答案在错误信息的第一部分:

The array type 'System.String[]' cannot be initialized in a query result.

它只是告诉你不能在查询 select 子句中使用数组(如果你问为什么,我不知道,这真的无关紧要 - 唯一重要的部分是它是您正在使用的库的要求)。

所以,错误的部分是

select new[] { x.name, x.Description, x.user }

解决方案在错误信息的第二部分:

Consider using 'System.Collections.Generic.List'1[System.String]` instead."

实际上,它是在告诉您使用 List 而不是数组。因此,要么

select new[] { x.name, x.Description, x.user }.ToList()

select new List<string> { x.name, x.Description, x.user }

将解决SQL查询翻译部分(消除异常)。

要获得所需的最终结果,您应该使用 AsEnumerable() 切换到 LINQ to Objects 上下文并将结果列表转换为数组:

var list =
(from x in table1
join y in table2 on x.Hid equals y.Hid
where x.Hid == hid
select new [] { x.name, x.Description, x.user }.ToList())
.AsEnumerable()
.Select(x => x.ToArray())
.ToList();

关于c# - Linq 查询创建字符串数组错误列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41732132/

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