简体   繁体   English

c# 嵌套循环 - 从列表中获取不同的元素(没有 Linq)

[英]c# nested loops- get distinct elements from List (without Linq)

If I have a List which contains some possibly duplicated string elements eg "dog","cat","dog","cow","cow","owl" .如果我有一个包含一些可能重复的字符串元素的列表,例如"dog","cat","dog","cow","cow","owl" I need to get the distinct elements from that list ( so I need to write the list of all elements without repetitive ones ie "dog","cat","cow","owl" ).我需要从该列表中获取不同的元素(因此我需要编写没有重复元素的所有元素的列表,即"dog","cat","cow","owl" )。 There must be a way how to use it with nested loops but I got stuck on something below:必须有一种方法可以将它与嵌套循环一起使用,但我陷入了以下问题:

IList<string> animals;
int a = animals.Count();
for (int i=0; i<a; i++)
   {
    foreach (string animal in animals)
    {
     if (animals[i+1] != animals[i])
      {
       Console.WriteLine(animals[i]);
       }
    }
  }

This is something close but it's not the correct one.这很接近,但不是正确的。 Perhaps the nested inner loop should be "while" or another "for".也许嵌套的内部循环应该是“while”或另一个“for”。 Appreciate any tip on above.感谢上面的任何提示。 Thanks!谢谢!

Use an HashSet<string> This class is similar to a List but doesn't allow duplicates使用HashSet<string>这个 class 类似于 List 但不允许重复

IList<string> animals = new List<string> {"Lion", "Wolf", "Tiger", "Dog", "Cat", "Lion", "Tiger"};
HashSet<string> uniques = new HashSet<string>(animals);
foreach(animal in uniques)
   Console.WriteLIne(animal);

If you want to use a loop you could simplify your code using a second list where you will store unique values and while at it you can also avoid false uniqueness when the only difference is case upper or lower in the animal name如果你想使用一个循环,你可以使用第二个列表来简化你的代码,你将在其中存储唯一值,而当唯一的区别是动物名称的大小写时,你还可以避免错误的唯一性

IList<string> animals = new List<string> {"Lion", "Wolf", "Tiger", "Dog", "Cat", "Lion", "tiger"};
List<string> uniques = new List<string>();
foreach (string animal in animals)
{
    if (!SearchCaseInsensitive(uniques, animal))
        uniques.Add(animal);
}
foreach(string animal in uniques)
    Console.WriteLine(animal);


bool SearchCaseInsensitive(List<string> source, string search)
{
    string lowerCaseSearch = search.ToLower();
    foreach(string animal in source)
        if(animal.ToLower() == lowerCaseSearch)
            return true;
    return false;
}

One way to achieve this would to use a loop to iterate the elements and add to another collection, each time you encounter a new one.实现这一点的一种方法是使用循环来迭代元素并添加到另一个集合中,每次遇到一个新集合。 For example,例如,

var unique = new List<string>();
foreach(var animal in animals)
{
    if(!unique.Contains(animal))
    {
        unique.Add(animal);
    }
}

foreach(var item in unique)
{
    Console.WriteLine(item);
}

If you collection contains too many elements, a Dictionary with a faster look up might be a better solution than List.如果您的集合包含太多元素,那么查找速度更快的 Dictionary 可能是比 List 更好的解决方案。 For example例如

var unique = new Dictionary<string,int>();
foreach(var animal in animals)
{
    if(!unique.ContainsKey(animal))
    {
        unique.Add(animal,1);
    }
}

foreach(var item in unique)
{
    Console.WriteLine(item.Key);
}

I'll recommend using HashSet.我会推荐使用 HashSet。

HashSet<string> uniqueAnimals = new HashSet<string>(animals);
List<string> animals new List<string> {"dog","cat","dog","cow","cow","owl"};  // your animals list

List<string> sorted = new List<string>();
foreach(string animal in animals)
{
     if (!sorted.Contains(animal))
      {
        sorted.Add(animal);
      }
}

Yet another HashSet<string> solution:另一个HashSet<string>解决方案:

HashSet<string> unique = new HashSet<string>();

foreach(var animal in animals)
  if (unique.Add(animal))
    Console.WriteLine(animal);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM