[英]Linq query to create list of string arrays error
我正在尝试创建一个字符串数组列表。 下面是代码。
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."
有谁能告诉我这里有什么问题。 任何帮助,将不胜感激 。
提前致谢
有谁能告诉我这里有什么问题
答案在错误消息的第一部分内:
无法在查询结果中初始化数组类型'System.String []'。
它只是告诉你不能在查询select
子句中使用数组(如果你问为什么,我不知道,并且它真的没关系 - 唯一重要的部分是它是你正在使用的库的要求) 。
所以,错误的部分是
select new[] { x.name, x.Description, x.user }
并且解决方案位于错误消息的第二部分内:
考虑使用'System.Collections.Generic.List'1 [System.String]`代替。“
实际上它告诉你使用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();
我认为你选择了一种失败方法来解决这个问题,你可以通过为新项目创建一个类来尝试类似下面的内容。
新类定义:
public class LinqResult
{
public string Name { get; set; }
public string Description { get; set; }
public string User { get; set; }
}
方法签名的变化:
public List<LinqResult> GetRec(int hid)
{
List<int> intList = new List<int>() { 1, 2, 5, 8, 9, 6, 3, 2, 4, 5, 6, 3, 2, 4, 855, 6, 2, 4, 6, 1, 56, 3 };
var list = (from x in table1
join y in table2 on x.Hid equals y.Hid
where x.Hid == hid
select new LinqResult
{
Name = x.name,
Description = x.Description,
User = x.user
}).ToList();
return list;
}
用法示例:
foreach (LinqResult item in GetRec(10))
{
Console.WriteLine("Name : {0} \n Description : {1} \n User : {2}", item.Name, item.Description, item.User);
}
嗯
这项工作可能吗?
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})
.Select(a => { return new string[] { a.Name, a.Description, a.User}; }).ToList();
return list;
}
我做过的类似程序。 所以,我认为你不需要制作任何包装类。 即使您不必使用列表而不是数组。
public class Records
{
public string Name;
public int Number;
public Records(string ticker, int number)
{
this.Name = ticker;
this.Number = number;
}
}
static void Main(string[] args)
{
List<Records> list = new List<Records>();
list.Add(new Records("amit", 1));
list.Add(new Records("bharat", 1));
list.Add(new Records("amit", 2));
list.Add(new Records("bhart", 2));
List<string[]> listStr = (from ele in list
where ele.Name == "amit"
select new[] { ele.Name, ele.Number.ToString() }).ToList();
}
这段代码给出了我想要的确切结果
所以我认为你需要在代码中看到更多内容,一定有问题。 您可以做的一件事是,在您的环境中尝试此代码以确认它不是因为您的目标框架或linq的dll(但它似乎不是这样,因为我在3.5和4.0中都尝试过这个)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.