【问题标题】:Using Linq To Convert ListBox Items Values to int使用 Linq 将 ListBox 项值转换为 int
【发布时间】:2009-05-13 05:05:12
【问题描述】:

我使用 ListBox 显示数据库中表的内容。每个列表框项都使用设置为友好名称的 Text 属性和设置为唯一 ID 列的 Value 属性填充。数据库结构可能类似于以下内容:

CREATE TABLE GENERIC { FRIENDLY_NAME TEXT, ID INT }

我尝试使用 LINQ 将列表框的项目转换为 int[] 将近一个小时,但最终失败了。区分已选项目和未选项目也很重要。这是我最后写的:

System.Collections.Generic.LinkedList<int> 
            selected = new LinkedList<int>(), 
            notSelected = new LinkedList<int>();

        foreach (ListItem item in PhotoGalleryEdit_PhotoShoots.Items)
        {
            if (item.Selected)
                selected.AddFirst(Convert.ToInt32(item.Value));
            else
                notSelected.AddFirst(Convert.ToInt32(item.Value));
        }

 int []arraySelected = selected.ToArray();
 int []arrayNotSelected = notSelected.ToArray();

谁能说明这是如何在 LINQ 中完成的?

(我所有的代码都是用 C# 编写的,但任何用 VB 编写的答案都非常受欢迎)

【问题讨论】:

    标签: c# asp.net linq listbox asp.net-3.5


    【解决方案1】:

    根据你的描述,我能想到的最不混乱的是:

    var qry = from ListItem item in listbox.Items
              select new {item.Selected, Value = Convert.ToInt32(item.Value)};
    
    int[] arrSelected=qry.Where(x=>x.Selected).Select(x=>x.Value).ToArray();
    int[] arrNotSelected=qry.Where(x=>!x.Selected).Select(x => x.Value).ToArray();
    

    由于您使用的是 AddFirst,因此您可能还需要在某处使用 .Reverse() - 或者之后使用 Array.Reverse()

    【讨论】:

      【解决方案2】:
      int[] selected = (from item in PhotoGalleryEdit_PhotoShoots.SelectedItems.OfType<MyItem>() select item.Value).ToArray();
      

      编辑:添加 OfType 调用以将选定的项目获取到 IEnumerable。

      编辑二:对于未选中的项目:

      int[] notSelected = (from item in PhotoGalleryEdit_PhotoShoots.Items.OfType<MyItem>() where !Array.Exists(selected, x => x == item.Value) select item.Value).ToArray();
      

      【讨论】:

      • SelectedItems 需要一个 Cast() 或类似的(它不是 IEnumerable) - 你已经放弃了 Convert.ToInt32
      • 我使用 IList 而不是 IList 进行了测试,您正确指出的是 SelectedItems 返回的内容。幸运的是,SelectedItems 有一个很好的 OfType 方法,它返回一个 IEnumerable 对象,使其成为一个很好的单行解决方案。
      猜你喜欢
      • 2014-11-08
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 2021-11-04
      • 2012-07-05
      • 2012-01-09
      相关资源
      最近更新 更多