Skip to main content
 首页 » 编程设计

c#之原地移除多次出现的 ListT> 元素

2024年02月05日17artech

有一个similar question posted ,但我没有代表在该线程中提出后续问题。 :(

如果我有一个 List<T>包含多次出现的项目,List.Distinct()将删除重复项,但原始文件仍将保留在原处。如果我想删除多次出现的项目,包括原始项目,对原始列表执行此操作的最有效方法是什么?

给定一个 List<int>称为 oneTime :

{ 4, 5, 7, 3, 5, 4, 2, 4 } 

所需的输出将在 oneTime 中:

{ 7, 3, 2 } 

跟进@Enigmativity 的问题:

这是我的脚本正在执行的操作的伪版本。它是在运行于 .NET3.5 上的 NinjaTrader 中完成的。

我将附上代码应该做什么的一般概念,我会附上实际的脚本,但除非使用 NinjaTrader,否则它可能没有用。

但本质上,有一个大的 z 循环。每次通过时,一系列数字都会添加到“LiTics”中。我不想打扰。然后我将该列表传递给函数,并返回只出现一次的值列表。然后我想在循环中每次都看到这些数字。

它最初可以工作,但是在不同的数据集上运行它,在循环几次之后,它开始报告出现不止一次的值。我不确定到底是为什么?

for(int z=1; z<=10000; z +=1)//Runs many times  
{  
    if (BarsInProgress ==0 &&CurrentBar-oBarTF1>0 &&startScript )   //Some Condition 
    { 
        for(double k=Low[0]; k<=High[0]; k +=TickSize)   
        {    
            LiTics.Add(k);   
            //Adds a series of numbers to this list each time through z loop 
            //This is original that I do not want to disturb 
        } 
 
        LiTZ.Clear();  //Display list to show me results Clear before populating 
        LiTZ=GetTZone(LiTics); //function created in thread(below) 
                               //Passing the undisturbed list that is modified on every loop 
        foreach (double prime in LiTZ) { Print(Times[0] +",  " +prime);  } 
        //Printing to see results    
    } 
 
}//End of bigger 'z' loop 
 
//Function created to get values that appear ONLY once 
public List<double> GetTZone(List<double> sequence)  
{   
    var result = 
        sequence 
            .GroupBy(x => x) 
            .Where(x => !x.Skip(1).Any()) 
            .Select(x => x.Key) 
            .ToList(); 
    return result; 
} 

一张打印输出的图片以及出了什么问题:Screenshot .

请您参考如下方法:

所以,如果你有一个新列表,那么这是最简单的方法:

var source = new List<int>() { 4, 5, 7, 3, 5, 4, 2, 4 }; 
 
var result = 
    source 
        .GroupBy(x => x) 
        .Where(x => !x.Skip(1).Any()) 
        .Select(x => x.Key) 
        .ToList(); 

这给出:

{ 7, 3, 2 } 

If you want to remove the values from the original source, then do this:

var duplicates = 
    new HashSet<int>( 
        source 
            .GroupBy(x => x) 
            .Where(x => x.Skip(1).Any()) 
            .Select(x => x.Key)); 
 
source.RemoveAll(n => duplicates.Contains(n));