簡體   English   中英

動態創建一個列表(或任何變量),向每個列表添加數據,然后在 C# 中比較它們

[英]create a list (or any variable) dynamically, add data to each list and later compare them in C#

我有一些字符串的list ,我想在循環內為每個字符串動態創建一個列表。

主要思想是通過循環從該list獲取每個字符串,並以該字符串作為名稱創建一個列表。 然后向其中添加一些數據。

例子:

   List<string> names = new List<string>(); // this is the main list with strings

   foreach (string nm in name)
   {
     // Here create a new list with this name
     // Add data to the list
   }  

   // Now, compare all of them to find duplicate data

   // Give message if any duplicate data found

更新:基本上,我將在運行時使用一些數據庫 API 將數據添加到list ,字符串名稱是該 API 中的鍵。 因此,對於主列表中的每個名稱,我將從數據庫中檢索一些數據,使用該名稱創建一個列表並向其中添加數據。 稍后我們將把它們放在一起比較。 所以基本問題仍然是我如何在運行時創建這些list

使用通用字典:

List<string> names = new List<string>(); // this is the main list with strings
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

foreach (string name in names)
{
    if (!dict.ContainsKey(name))
        dict.Add(name, new List<string>());
    dict[name].Add("another one bytes the dust :)");
}  

在上面的示例中,您將擁有一個字典,其鍵的數量等於唯一名稱的數量,並且您可以通過關聯列表中具有多個項目的鍵來查找重復項。

例如:

string[] dupes = dict.Keys.ToList().Find(k => dict[k].Count > 1).ToArray();

使用 Linq to Object 判斷列表是否有重復記錄

bool IsDuplicate  = (names.Count != names.Distinct().Count());

if(IsDuplicate) {
    // Message : List has duplicate values.
}

祝你好運

您可以使用IList<KeyValuePair<String,IList<SomethingData>>>Hastable<String,IList<SomethingData>>

 //fill data to lists
 IList<KeyValuePair<String,IList<SomethingData>>> dataSets=new  List<KeyValuePair<String,IList<SomethingData>>>();
 IList<string> names = new List<String>();
 foreach (string nm in names)
 {
     IList<SomethingData> data = new List<SomethingData>();
     //...fill data
     dataSets.Add(new KeyValuePair<string, IList<SomethingData>>(nm, data));
 } 

 //search lists by name
 String nameForSearch = "test";
 IEnumerable<KeyValuePair<String,IList<SomethingData>>> dataSetsByName = dataSets.Where(ds => ds.Key == nameForSearch);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM