C# 如何使用多选列表?

C# 如何使用多选列表?,c#,linq,multi-select,linqpad,C#,Linq,Multi Select,Linqpad,我得到以下编译错误: 参数2:无法从“System.Collections.Generic.IEnumerable”转换为“string” 参数3:无法从“System.Collections.Generic.IEnumerable”转换为“string” 如何修复此错误 void Main() { SortedDictionary<int, string> items = new SortedDictionary<int, string>{{1, "a

我得到以下编译错误:

参数2:无法从“System.Collections.Generic.IEnumerable”转换为“string”

参数3:无法从“System.Collections.Generic.IEnumerable”转换为“string”

如何修复此错误

void Main()
{
    SortedDictionary<int, string> items = new SortedDictionary<int, string>{{1, "apple"}, {2, "book"}, {3, "tree"}, {4, "mazagine"}, {5, "orange"}};
    MultiSelectList msl = new MultiSelectList(items, items.Select(o => o.Key), items.Select(o => o.Value), items.Where(i => i.Key == 1 || i.Key == 5)).Dump();
}
构造函数需要四个参数:

项目集合-您正在正确传递它们 dataValueField字符串-这是您的第一个错误。您应该传递值字段的名称,而不是传递所有值。 dataTextField字符串-这是第二个错误。您应该传递文本字段的名称,而不是传递所有文本值。 selectedValues集合-这是您的第三个错误。您应该只传递1和5的值,而不是传递具有选定值的项。 所以,正确的代码是

new MultiSelectList(items, "Key", "Value", new [] { 1, 5 })

我建议您仔细阅读错误消息,查看IntelliSense提示,并使用获取有关您正在使用的类型的信息。

错误消息中有哪些不清楚的地方?如果你描述一下你对他们的理解,我们可能会帮助你。这个错误是不言自明的。。您正在传递一个需要字符串的集合。请尝试新建MultiSelectListitems、Key、Value、new[]{1,5}Sergey Berezovskiy,您的答案是正确的。谢谢!这样也行。MultiSelectList msl1=新的MultiSelectList项、键、值、项。选择o=>o.Key.Whereo=>o==1 | | o==5.Dump@Matthew是的,如果某些选定值可能无法显示在项目中,则这一点更好