【问题标题】:Select a Single Column from an Object Observable collection从 Object Observable 集合中选择单列
【发布时间】:2013-03-07 07:32:06
【问题描述】:

我有一个ObservableCollection,在运行时填充了 4 列。

public ObservableCollection<object> SelectedRows;

我想从此集合中获取 Id 列值,但我无法使用 LINQ 获取此值,因为在编译时我不知道集合中存在 Id 列。

【问题讨论】:

    标签: c# wpf selection observablecollection


    【解决方案1】:

    可能是这样的:

    vat w = from s in db.table
            select s.id;
    
    foreach (var i in w)
    { 
        console.writeln(i);
    }
    

    【讨论】:

    • 它不会工作,因为 s.id 不可用。此 ID 在声明时未给出,在运行时未给出。
    • 这对我有用:var selectedIndexId = from itemSelectedRows in LstIndexId.ToList() select itemSelectedRows.GetType().GetProperty("Id").GetValue(itemSelectedRows, null);跨度>
    【解决方案2】:
    var selectedIndexId = from itemSelectedRows in <YourListName>.ToList<object>()
                          select itemSelectedRows.GetType().GetProperty("Id").GetValue(itemSelectedRows, null);
    

    【讨论】:

      【解决方案3】:

      您可以使用数据绑定来做到这一点:

      <ListBox ItemsSource="{Binding SelectedRows}"
               DisplayMemberPath="The property to be displayed"
               SelectValuePath="The property that SelectedValue would bind to"
               SelectedValue="{Binding SelectedRowId}" />
      

      如果您需要在 C# 中执行此操作,我强烈建议您的对象实现一个可以转换为的通用接口。否则,您可以使用dynamic 关键字:

      SelectedRows.Cast<dynamic>().Select(d => (int)d.Id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多