[英]Check same elements in two lists
我有一個List和一個ListItemCollection,想檢查是否有相同的元素。
首先,我用文本和值填充ListItemCollection。 (在執行SQL Select之后)
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值,並從值adn中讀取文本並將其寫入新列表中。
注意:我使用asp.net 2.0。
List.FindAll
在C#2.0中已經可用:
List<string> newList = tempList.FindAll(s => tempListName.FindByText(s) != null);
ListItemCollection.FindByText
:
使用FindByText方法在集合中搜索具有Text屬性的ListItem,該ListItem屬性等於text參數指定的文本。 此方法執行區分大小寫和不區分文化的比較。 此方法不執行部分搜索或通配符搜索。 如果使用此條件在集合中找不到項目, 則返回null 。
真正簡單的解決方案,您可以根據需要進行自定義和優化。
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);
}
}
}
因此,對於一個真實的簡單示例,請考慮以下內容:
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>();
var resultList = new List<string>();
foreach (string listItem in tempList)
foreach (ListItem listNameItem in tempListName)
if (listNameItem.Value.Equals(listItem))
resultList.Add(listNameItem.Text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.