我有列表,我想将其转换为autoCompleteStringCollection。而且我也不想使用foreach。
_textbox.AutoCompleteMode = AutoCompleteMode.Append;
_textbox.AutoCompleteSource = AutoCompleteSource.CustomSource;
_textbox.AutoCompleteCustomSource = user.GetNameUsers() as AutoCompleteStringCollection;
注意user.GetNameUsers()是列表。
代码不起作用,它变为空。
谢谢
最佳答案
_textbox.AutoCompleteMode = AutoCompleteMode.Append;
_textbox.AutoCompleteSource = AutoCompleteSource.CustomSource;
var autoComplete = new AutoCompleteStringCollection();
autoComplete.AddRange(user.GetNameUsers().ToArray());
_textbox.AutoCompleteCustomSource = autoComplete;
如果经常需要,可以编写扩展方法:
public static class EnumerableExtensionsEx
{
public static AutoCompleteStringCollection ToAutoCompleteStringCollection(
this IEnumerable<string> enumerable)
{
if(enumerable == null) throw new ArgumentNullException("enumerable");
var autoComplete = new AutoCompleteStringCollection();
foreach(var item in enumerable) autoComplete.Add(item);
return autoComplete;
}
}
用法:
_textbox.AutoCompleteCustomSource = user.GetUsers().ToAutoCompleteStringCollection();