C# - 将IEnumerable转换为Dictionary <object,string>

时间:2015-11-20 17:11:42

标签: c# wpf

我正在构建一个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&gt;在这个功能:

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();           
    }

我如何进行过渡?

修改 更多信息: 我的viewmodel有这个属性:

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"/>

2 个答案:

答案 0 :(得分:6)

[S]好的。你发布了很多代码(我个人认为这对你正在尝试做的事情是不必要的)。

让它变瘦吧。

你有IEnumerable<string>开始,对吗?好。

LINQ库中有ToDictionary()扩展方法。文档为here

所以你需要做的是:

IEnumerable<string> myEnumerableOfStrings = new List<string>();

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

And here's a Fiddle as an example.

好吧,我们只有一个没有强类型的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());
}

Here's an example of that.

答案 1 :(得分:0)

上面关于 ToDictionary 扩展的答案示例,是原始类型(字符串)的列表,我想演示如何将复杂类型(类)的列表转换为字典。

这个重载正在用 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);