我在有序数组上使用LINQ to Objects指令.我不应该做哪些操作来确保数组的顺序没有改变?
假设我有一个包含重复值的List,我想删除重复项.
List<int> myList = new List<int>(Enumerable.Range(0, 10000));
// adding a few duplicates here
myList.Add(1);
myList.Add(2);
myList.Add(3);
Run Code Online (Sandbox Code Playgroud)
我找到了3种方法来解决这个问题:
List<int> result1 = new HashSet<int>(myList).ToList(); //3700 ticks
List<int> result2 = myList.Distinct().ToList(); //4700 ticks
List<int> result3 = myList.GroupBy(x => x).Select(grp => grp.First()).ToList(); //18800 ticks
//referring to pinturic's comment:
List<int> result4 = new SortedSet<int>(myList).ToList(); //18000 ticks
Run Code Online (Sandbox Code Playgroud)
在SO的大多数答案中,Distinct方法显示为"正确的",但HashSet总是更快!
我的问题:当我使用HashSet方法时,有什么我必须要注意的,还有另一种更有效的方法吗?
使用VS2010构建时,以下C#代码似乎比使用VS2008 运行速度慢:在Core i5 Win7 x64 8 GB RAM PC上,VS2008内置版本在大约7.5秒内对字符串进行排序,而VS2010内置版本需要大约9秒.这是为什么?
我的代码有什么问题吗?
排序算法是否在VS2010中发生了变化?
底层CLR中有什么不同会使性能变差吗?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace StringSortCSharp
{
/// <summary>
/// Console app to test string sorting performance in C#.
/// </summary>
class Program
{
/// <summary>
/// Displays the first lines from a vector of strings.
/// </summary>
/// <param name="wishedN">Number of lines to display.</param>
/// <param name="lines">Source lines to display.</param>
private static void DisplayFirst(int wishedN, List<string> lines)
{
int …Run Code Online (Sandbox Code Playgroud) 我正在关注stackoverflow上的一篇关于从C#中的List中删除重复项的帖子.
如果<T>是某些用户定义类型,如:
class Contact
{
public string firstname;
public string lastname;
public string phonenum;
}
Run Code Online (Sandbox Code Playgroud)
建议的(HashMap)不会删除重复.我想,我必须重新定义一些比较两个对象的方法,不是吗?