如何在Select和/或SelectMany中保持初始化列表顺序

时间:2016-10-03 19:38:45

标签: c# linq

我希望这不是重复,但我无法找到答案。 它或者似乎是一种不受欢迎的行为,或者是我缺乏的知识。

我有一个平台和配置对象列表。两者都包含成员字符串CodeName。 CodeNames列表如下所示:

dbContext.Platforms.Select(x => x.CodeName) => {"test", "PC", "Nintendo"}
dbContext.Configurations.Select(x => x.CodeName) => {"debug", "release"}

它们是从MySQL数据库获得的,因此是dbContext对象。

这是一个简单的代码,我要在LINQ中翻译,因为2个foreach是过去的事情:

var choiceList = new List<List<string>>();
foreach (Platform platform in dbContext.Platforms.ToList())
{
    foreach (Configuration configuration in dbContext.Configurations.ToList())
    {
        choiceList.Add(new List<string>() { platform.CodeName, configuration.CodeName });
    }
}

这段代码完全符合我的要求,首先保持平台名称,如下所示:

var results = new List<List<string>>() {
{"test", "debug"},
{"test", "release"},
{"PC", "debug"}
{"PC", "release"}
{"Nintendo", "debug"}
{"Nintendo", "release"}};

但如果我将其翻译成这个,我的列表包含不同顺序的项目:

var choiceList = dbContext.Platforms.SelectMany(p => dbContext.Configurations.Select(t => new List<string>() { p.CodeName, t.CodeName })).ToList();

我最终会得到这个,平台名称始终不是第一个,这不是所希望的:

var results = new List<List<string>>() {
{"debug", "test"},
{"release", "test"},
{"debug", "PC"}
{"PC", "release"}
{"debug", "Nintendo"}
{"Nintendo", "release"}};

我的问题是,是否可以使用LINQ获得所需的结果?

如果我不清楚或者我的问题缺乏某些细节,请告诉我。 感谢

编辑:所以Ivan找到了解释,我修改了我的代码。 实际上,只有SelectMany前面的Enumerable需要.ToList()。 我还应该提到我需要一个List&gt;。

感谢大家的快速投入,非常感谢。

3 个答案:

答案 0 :(得分:1)

而不是将它投影到数组中,而是将它投影出两个带有两个字段的新对象(可能是一个匿名对象)然后,如果需要,可以在检索后将其投影到一个双元素数组中数据库中的对象,如果确实需要数组中的这些值。

答案 1 :(得分:1)

使用时

var choiceList = dbContext.Platforms.SelectMany(p => dbContext.Configurations.Select(t => new List<string>() { p.CodeName, t.CodeName })).ToList();

它真的被翻译成一些SQL查询,其中一旦你不使用ORDER BY就没有定义返回记录的顺序。

要获得与嵌套循环相同的结果,请执行并实现两个查询,然后在内存中执行SelectMany

var platforms = dbContext.Platforms.ToList();
var configurations = dbContext.Configurations.ToList();
var choiceList = platforms.SelectMany(p => configurations,
    (p, c) => new List<string>() { p.CodeName, c.CodeName })
    .ToList();

答案 2 :(得分:0)

试试这个 -

var platforms= dbContext.Platforms.Select(x=>x.CodeName);
var configurations=dbContext.Configurations.Select(x=>x.CodeName);

var mix=platforms.SelectMany(num => configurations, (n, a) => new { n, a });

如果您想详细了解更多信息 - Difference between Select and SelectMany

相关问题