C# 查询列表以仅查找重复项

C# 查询列表以仅查找重复项,c#,linq,list,C#,Linq,List,我在.NET3.5项目中有一个字符串类型列表。列表中有数千个字符串,但为了简洁起见,我们将说它只有5个字符串 List<string> lstStr = new List<string>() { "Apple", "Banana", "Coconut", "Coconut", "Orange"}; List lstStr=新列表(){ “苹果”、“香蕉”、“椰子”、“椰子”、“橙子”}; 假设列表已排序(如上所述)。我需要的是一个LINQ查询,

我在.NET3.5项目中有一个字符串类型列表。列表中有数千个字符串,但为了简洁起见,我们将说它只有5个字符串

List<string> lstStr = new List<string>() {
            "Apple", "Banana", "Coconut", "Coconut", "Orange"};
List lstStr=新列表(){
“苹果”、“香蕉”、“椰子”、“椰子”、“橙子”};
假设列表已排序(如上所述)。我需要的是一个LINQ查询,它将删除所有不重复的字符串。因此,结果将留给我一个只包含两个“couch”字符串的列表


这可以通过LINQ查询实现吗?如果不是,那么我将不得不求助于一些复杂的for循环,我可以这样做,但我不想这样做,除非我不得不这样做。

var dupes=lstStr.Where(x=>lstStr.Sum(y=>y==x?1:0)>1)

var dupes=lstStr.Where((x,i)=>((i>0&&x==lstStr[i-1]))
||(i
请注意,第一个为每一个花费O(n²)时间的元素枚举列表(但不采用排序列表)。第二个为O(n)(并采用排序列表)。

var temp=new list();
foreach(列表中的变量项)
{
var stuff=(来自列表中的m)
其中m==项
选择m);
if(stuff.Count()>1)
{
温度=温度混凝土(材料);
}
}
这应该是可行的,并且是O(N),而不是其他答案的O(N^2)。(注意,这确实使用了列表已排序的事实,因此这确实是一个要求)

IEnumerable OnlyDups(此IEnumerable coll)
其中T:i可比较
{
IEnumerator iter=coll.GetEnumerator();
if(iter.MoveNext())
{
T last=iter电流;
while(iter.MoveNext())
{
if(iter.Current.CompareTo(last)==0)
{
收益率最后;
做
{
产生返回iter电流;
}
while(iter.MoveNext()&&iter.Current.CompareTo(last)==0);
}
last=国际热核实验堆电流;
}
}
像这样使用它:

IEnumerable<string> onlyDups = lstStr.OnlyDups();
IEnumerable onlyDups=lstStr.onlyDups();

List onlyDups=lstStr.onlyDups().ToList();

以下是从字符串arrya中查找重复项的代码

int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
var duplicates = listOfItems
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);
foreach (var d in duplicates)
    Console.WriteLine(d);

@McKay:是的,但OP声明可以假设列表已排序。@McKey(修订问题):技术上不是,但它保留了linq样式的接口,可以用作更大的linq语句的一部分。
IEnumerable<T> OnlyDups<T>(this IEnumerable<T> coll) 
   where T: IComparable<T>
{
     IEnumerator<T> iter = coll.GetEnumerator();
     if (iter.MoveNext())
     {
         T last = iter.Current;
         while(iter.MoveNext())
         {
             if (iter.Current.CompareTo(last) == 0)
             {
                  yield return last;
                  do 
                  {
                       yield return iter.Current;
                  }
                  while(iter.MoveNext() && iter.Current.CompareTo(last) == 0);
             }
             last = iter.Current;
         }
}
IEnumerable<string> onlyDups = lstStr.OnlyDups();
List<string> onlyDups = lstStr.OnlyDups().ToList();
int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
var duplicates = listOfItems
    .GroupBy(i => i)
    .Where(g => g.Count() > 1)
    .Select(g => g.Key);
foreach (var d in duplicates)
    Console.WriteLine(d);