我希望這不是重複的,但我無法在此找到答案。它似乎是我不想要的行爲或缺少的知識。如何在Select和/或SelectMany中保持初始化程序列表順序
我有一個平臺和配置對象的列表。兩者都包含一個成員字符串CodeName。 版本代號的列表如下所示:
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>的需要所困住。
感謝大家的快速輸入,這真的很感謝。
如果你投射到一個強類型('新{平臺= ... ,配置= ...}'而不是一個字符串列表?你能發佈生成的SQL嗎?看起來很奇怪的是,這個命令會不一致。 –
@DStanley你會期望什麼命令結構生成代碼在SQL中?我期望它創建一個包含這兩個元素的新包,因爲這幾乎是SQL真正使用的唯一集合,並且除非明確排序,否則它本身是無序的。 – Servy
嘗試2個foreach在最後沒有ToList的情況下循環,你會看到相同的行爲。 – sachin