谁有一个快速的方法去重复在c#的泛型列表?


当前回答

我喜欢使用这个命令:

List<Store> myStoreList = Service.GetStoreListbyProvince(provinceId)
                                                 .GroupBy(s => s.City)
                                                 .Select(grp => grp.FirstOrDefault())
                                                 .OrderBy(s => s.City)
                                                 .ToList();

我的列表中有这些字段:Id、StoreName、City、PostalCode 我想在一个有重复值的下拉列表中显示城市。 解决方案:按城市分组,然后选择列表中的第一个城市。

其他回答

David J。的答案是一个很好的方法,不需要额外的对象,排序等。但是,它可以在以下方面进行改进:

for (int innerIndex = items.计数 - 1;内索引 > 外索引 ;内部索引--)

因此,对于整个列表,外部循环会从上到下,但内部循环会从下到“直到到达外部循环的位置”。

外部循环确保整个列表被处理,内部循环找到实际的重复项,这些只会发生在外部循环还没有处理的部分。

或者如果你不想对内循环做自底向上你可以让内循环从outerIndex + 1开始。

正如kronoz在. net 3.5中所说,您可以使用Distinct()。

在。net 2中,你可以模仿它:

public IEnumerable<T> DedupCollection<T> (IEnumerable<T> input) 
{
    var passedValues = new HashSet<T>();

    // Relatively simple dupe check alg used as example
    foreach(T item in input)
        if(passedValues.Add(item)) // True if item is new
            yield return item;
}

这可用于删除任何集合,并将以原始顺序返回值。

通常,过滤一个集合(Distinct()和这个示例都是这样做的)比从其中删除项要快得多。

把它排序,然后检查两个和两个相邻的,因为重复的会聚集在一起。

就像这样:

list.Sort();
Int32 index = list.Count - 1;
while (index > 0)
{
    if (list[index] == list[index - 1])
    {
        if (index < list.Count - 1)
            (list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);
        list.RemoveAt(list.Count - 1);
        index--;
    }
    else
        index--;
}

注:

从后到前进行比较,避免每次移除后都要列出度假胜地列表 这个例子现在使用c#值元组来进行交换,如果你不能使用它,可以用适当的代码来代替 最终结果不再排序

作为一个辅助方法(没有Linq):

public static List<T> Distinct<T>(this List<T> list)
{
    return (new HashSet<T>(list)).ToList();
}

有很多方法可以解决列表中的重复问题,下面是其中之一:

List<Container> containerList = LoadContainer();//Assume it has duplicates
List<Container> filteredList = new  List<Container>();
foreach (var container in containerList)
{ 
  Container duplicateContainer = containerList.Find(delegate(Container checkContainer)
  { return (checkContainer.UniqueId == container.UniqueId); });
   //Assume 'UniqueId' is the property of the Container class on which u r making a search

    if(!containerList.Contains(duplicateContainer) //Add object when not found in the new class object
      {
        filteredList.Add(container);
       }
  }

干杯 拉维Ganesan