编辑:由于 OP 对问题和其他人提出的后续问题进行了编辑,因此我编辑了我的答案。
首先,List 到 LinkedList 没有任何隐式或显式转换。
但是,以下演示代码可以编译。虽然这与 OP 提出的问题并不完全相同,但我已经分解了这些步骤。
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
namespace linkedlist
{
class Program
{
static void Main(string[] args)
{
var arr = new [] { "first", "second", "third" };
var q1 = from x in arr
select x;
var q = q1.ToList();
var ll = new LinkedList<string>(q);
}
}
}
为什么不直接使用 List,除非您正在执行很多操作,LinkedList 与 List 相比是最佳的(参见 SO query and answers on List vs LinkedList)?
最后一条语句创建了一个新的LinkedList<T>,它复制了List<T> 的内容。
如果目的是从 LINQ 查询中获取 LinkedList,则以下内容会减少浪费:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var arr = new [] { "first", "second", "third" };
var q1 = from x in arr
select x;
var ll = new LinkedList<string>(q1);
}
实验
这里是一些关于性能的数据
Linq 到 List<T> 到 LinkedList<T> 与 Linq 到 LinkedList<T>
实验代码
using System;
using System.Linq;
using System.Collections.Generic;
using System.Data.Entity;
namespace linkedlist
{
class Program
{
static void Main(string[] args)
{
var arr = new[] { "first", "second", "third" };
var q1 = from x in arr
select x;
for(var j = 0; j < 10; j++)
{
var st1 = DateTime.Now;
for (var i = 0; i < 10000; i++)
{
var q = q1.ToList();
var ll = new LinkedList<string>(q);
}
var en1 = DateTime.Now;
Console.WriteLine($"With LINQ to List<T> to LinkedList<T> {(en1 - st1).TotalMilliseconds}");
var st2 = DateTime.Now;
for (var i = 0; i < 10000; i++)
{
var ll = new LinkedList<string>(q1);
}
var en2 = DateTime.Now;
Console.WriteLine($"With LinQ to LinkedList<T> {(en2 - st2).TotalMilliseconds}");
}
}
}
}
计时结果:
截图:
应该忽略第一次运行以降低缓存预热效果,因为我们对两个测试使用相同的 LINQ 查询。对于每次试验 10,000 次迭代和总共 10 次试验,所有时间都是总经过的毫秒数。
With LINQ to List<T> to LinkedList<T> 20.0769
With LinQ to LinkedList<T> 8.6571
With LINQ to List<T> to LinkedList<T> 12.0162
With LinQ to LinkedList<T> 8.7212
With LINQ to List<T> to LinkedList<T> 12.7354
With LinQ to LinkedList<T> 8.3412
With LINQ to List<T> to LinkedList<T> 12.6848
With LinQ to LinkedList<T> 8.1306
With LINQ to List<T> to LinkedList<T> 12.3656
With LinQ to LinkedList<T> 8.5935
With LINQ to List<T> to LinkedList<T> 19.8802
With LinQ to LinkedList<T> 7.9596
With LINQ to List<T> to LinkedList<T> 12.1177
With LinQ to LinkedList<T> 9.0604
With LINQ to List<T> to LinkedList<T> 18.219
With LinQ to LinkedList<T> 11.115
With LINQ to List<T> to LinkedList<T> 18.4309
With LinQ to LinkedList<T> 11.2717
With LINQ to List<T> to LinkedList<T> 18.6743
With LinQ to LinkedList<T> 11.4202
结论:
Linq to LinkedList 比 Linq to List to LinkedList 更快,浪费更少。