C#-将IEnumerable转换为Dictionary<;对象,字符串>;

本文关键字:对象 字符串 gt lt 转换 Dictionary C#- IEnumerable | 更新日期: 2023-09-27 18:23:35

我正在构建一个WPF UserControl。为此,我实现了一个类似的ItemSource DependecyProperty

private IEnumerable MisItems;
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(TextBoxAutoComplete), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
    private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var control = sender as TextBoxAutoComplete;
        if (control != null)
            control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
    }
    private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        MisItems = newValue;
        // Remove handler for oldValue.CollectionChanged
        var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
        if (null != oldValueINotifyCollectionChanged)
        {
            oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
        }
        // Add handler for newValue.CollectionChanged (if possible)
        var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
        if (null != newValueINotifyCollectionChanged)
        {
            newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
        }
    }
    void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //Do your stuff here.
    }

ItemsSource属性由IEnumerable对象表示。现在我需要在以下函数中将其转换为Dictionary<object,string>:

protected SearchResult DoSearch(string searchTerm)
    {
        if (!string.IsNullOrEmpty(searchTerm))
        {
            SearchResult sr = new SearchResult();
            //var ItemsText = MisItems.GetType();
            var p = (List<string>)MisItems;
             /*sr.Results = ItemsText.Select((x, i) => new { x, i }).Where(x=>x.ToString().ToUpper().Contains(searchTerm.ToUpper()))
            .ToDictionary(a => (object)a.i, a => a.x);*/
            return sr;
        }
        else return new SearchResult();           
    }

我该如何过渡?

编辑更多信息:我的视图模型具有以下属性:

public List<EnumeradorWCFModel> Clientes { get; set; }

此属性的数据由WCF service:返回

Clientes = _svc.Clientes_Enum(sTicket, "");

然后我希望我的UserControl绑定到此属性。我这样创建我的控件:

<autocomplete:TextBoxAutoComplete x:Name="Clientes"  ItemsSource = "{Binding Path=Clientes}" DisplayMemberPath="Descripcion" Height="25"/>

C#-将IEnumerable转换为Dictionary<;对象,字符串>;

[s]好的。你发布了很多代码(我个人认为这对你想要做的事情来说是不必要的)。

让我们减肥吧。

你有一个IEnumerable<string>开始,对吗?好的

LINQ库中有一个ToDictionary()扩展方法。文档在这里。

所以你需要做的是:

IEnumerable<string> myEnumerableOfStrings = new List<string>();
Dictionary<object, string> dictionary = myEnumerableOfStrings.ToDictionary(value => (object) value);

这里有一个Fiddle作为例子。

好的,我们只有一个没有强类型的IEnumerable。(我第一次看到或听说这样做,但同样的原则应该适用。)

我们需要创建一个本地字典并对该集合进行迭代。

var myDictionary = new Dictionary<object, string>();
IEnumerable myCollection = new List<string>();
foreach(var item in myCollection)
{
    // This might be fun if you get two of the same object in the collection.
    // Since this key is based off of the results of the GetHashCode() object in the base object class.
    myDictionary.Add((object) item, item.ToString());
}

这是一个例子。

以上ToDictionary扩展的答案示例是基元类型(字符串)的List,我想演示将复杂类型(类)的List转换为字典。

这个重载正在用keySelector函数和elementSelector函数(docs)构造一个字典:

public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector);

例如:

public class FooClass 
{
    public int FooKey { get; set; }
    public string FooValue { get; set; }
}
IENumerable<FooClass> foos = new List<FooClass>();
IDictionary<int, string> dict = foos.ToDictionary<int, string>(x=>x.FooKey, x=>x.FooValue);