2

我有一个 List 和一个 ListItemCollection 并想检查是否有相同的元素。

首先,我用文本和值填充 ListItemCollection。(在 SQL 选择之后)

ListItemCollection tempListName = new ListItemCollection();
ListItem temp_ListItem;

    if (reader.HasRows)
    {
       while (reader.Read())
       {
          temp_ListItem = new ListItem(reader[1].ToString(), reader[0].ToString());
          tempListName.Add(temp_ListItem);
       }
    }

我有清单

List<string> tempList = new List<string>(ProfileArray);

有一些值,如 {"1","4","5","7"}

现在,我想检查一下 tempList 是否在 tempListName 中可能有一些具有相同值的元素,并从值中读取文本并将其写入新列表中。

注意:我使用的是 asp.net 2.0。

4

4 回答 4

4

List.FindAll在 C# 2.0 中已经可用:

List<string> newList = tempList.FindAll(s => tempListName.FindByText(s) != null);

ListItemCollection.FindByText

使用 FindByText 方法在集合中搜索具有 Text 属性的 ListItem,该属性等于由 text 参数指定的文本。此方法执行区分大小写和不区分区域性的比较。此方法不执行部分搜索或通配符搜索。如果使用此条件在集合中未找到项目,则返回 null

于 2013-08-15T12:28:09.147 回答
1

真正简单的解决方案,您可以根据需要进行自定义和优化。

List<string> names = new List<string>(); // This will hold text for matched items found
foreach (ListItem item in tempListName)
{
    foreach (string value in tempList)
    {
        if (value == item.Value)
        {
            names.Add(item.Text);
        }
    }
}
于 2013-08-15T12:35:53.300 回答
0

所以,对于一个真正简单的例子,考虑这样的事情:

List<string> tempTextList = new List<string>();

while (reader.Read())
{
    string val = reader[0].ToString(),
        text = reader[1].ToString();

    if (tempList.Contains(val)) { tempTextList.Add(text); }

    temp_ListItem = new ListItem(text, val);
    tempListName.Add(temp_ListItem);
}

现在,仅仅列出文本值并没有什么好处,所以让我们稍微改进一下:

Dictionary<string, string> tempTextList = new Dictionary<string, string>();

while (reader.Read())
{
    string val = reader[0].ToString(),
        text = reader[1].ToString();

    if (tempList.Contains(val)) { tempTextList.Add(val, text); }

    temp_ListItem = new ListItem(text, val);
    tempListName.Add(temp_ListItem);
}

现在,您实际上可以从字典中找到特定值的文本。您甚至可能想Dictionary<string, string>在更高的范围内声明它并在其他地方使用它。如果您要在更高的范围内声明它,您只需更改一行,即:

Dictionary<string, string> tempTextList = new Dictionary<string, string>();

对此:

tempTextList = new Dictionary<string, string>();
于 2013-08-15T12:28:37.373 回答
0
        var resultList = new List<string>();
        foreach (string listItem in tempList)
            foreach (ListItem listNameItem in tempListName)
                if (listNameItem.Value.Equals(listItem))
                    resultList.Add(listNameItem.Text);
于 2013-08-15T12:39:32.077 回答