2

我使用 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 编写的答案都非常受欢迎)

4

2 回答 2

6

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

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()之后使用。

于 2009-05-13T05:20:27.457 回答
0
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();
于 2009-05-13T05:15:15.437 回答