【问题标题】:How can i select elements from an IEnumerable to store them in another IEnumerable?如何从 IEnumerable 中选择元素以将它们存储在另一个 IEnumerable 中?
【发布时间】:2017-11-22 15:15:48
【问题描述】:

我已经构建了一个自定义用户控件,它有一个 IEnumerable 作为输入,它还应该返回一个 IEnumerable。这是为了有一个灵活的控件,可以接收任何对象的集合。这里有一些代码 sn-ps 可以帮助你理解我的问题:

  • 物品来源

    public static readonly DependencyProperty ItemsSourceProperty =
    DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(MultiSelectionComboBox), new PropertyMetadata(
    new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
    
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }
    
  • 所选项目

    public static readonly DependencyProperty SelectedItemsProperty =
    DependencyProperty.Register("SelectedItems", typeof(IEnumerable), typeof(MultiSelectionComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
    new PropertyChangedCallback(MultiSelectionComboBox.OnSelectedItemsChanged)));
    
    public IEnumerable SelectedItems
    {
        get { return (IEnumerable)GetValue(SelectedItemsProperty); }
        set
        {
            SetValue(SelectedItemsProperty, value);
        }
    }
    

除了构建 SelectedItems 属性的部分之外,我能够让我的控制工作

foreach(string s in appo)
{
  IEnumerator en = ItemsSource.GetEnumerator();
  while (en.MoveNext())
  {
      var val = en.Current;
      Type type = val.GetType();
      PropertyInfo property = type.GetProperty(DisplayMemberPath);
      if (property != null)
      {
          string name = (string)property.GetValue(val, null);
          if(name == s)
          {
              // need something here          
          }
      }
   }
}

基本上在if 中,我检查了IEnumeratoren 的当前元素必须包含在SelectedItem 中。问题是我不知道如何在输出中包含这个元素(即 SelectedItems)。

如果您有更好的想法,我也愿意接受不同的方法

【问题讨论】:

  • 如果您希望能够将元素添加到现有的 SelectedItems 集合(而不是创建新集合),请将其类型更改为 ICollection,它具有 Add、Remove 和 Clear 方法。
  • 不要使用 GetEnumerator 的东西;使用foreach (var val in ItemsSource) {
  • 它是直接从 IEnumerable 派生的接口,具有添加或删除元素的附加协定。
  • @DanieleSartori 谁提供 SelectedItems 中的集合?如果您创建IList 类型,则强制要求他们必须提供实现IList 中所有方法和属性的东西——包括Add()。实际上,您是在坚持他们为您提供某种允许您向其中添加项目的集合类。
  • @DanieleSartori 请改用IList

标签: c# wpf ienumerable


【解决方案1】:

问题是IEnumerable 没有添加项目的能力。因此,您需要将其更改为具有 Add 方法的对象,例如 IListICollection<object>

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2011-10-12
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多