我需要找到每个索引。除了遍历所有项目之外,最优雅和最有效的方法是什么。我在.NET4.0上,所以LINQ是一个选项。我做了很多搜索和连接,但一无所获。示例数据:vardata=newList{"fname","lname","home","home","company"}();我需要获取“家”的索引。您可以从包含其索引的每个项目创建一个对象,然后对值进行分组并过滤掉包含多个对象的组。您现在有一个包含包含文本及其原始索引的对象的分组列表:varduplicates=data.Select((t,i)=>new{Index=i,Text=t}).GroupBy(g=>g.Text).Where(g=>g.Count()>1);使用系统;使用System.Collections.Generic;类程序{staticvoidMain(string[]args){vardata=newList{“fname”,“lname”,“home”,“home”,“company”};foreach(varduplicateinFindDuplicates(data)){Console.WriteLine("Duplicate:{0}atindex{1}",duplicate.Item1,duplicate.Item2);}}publicstaticIEnumerable>FindDuplicates(IEnumerabledata){varhashSet=newHashSet();整数索引=0;foreach(varitemindata){if(hashSet.Contains(item)){yieldreturnTuple.Create(item,index);}else{hashSet.Add(item);}索引++;}}}这样的事情怎么样?vardata=newList{"fname","lname","home","home","company"};varduplicates=data.Select((x,index)=>new{Text=x,index}).Where(x=>(data.GroupBy(i=>i).Where(g=>g.Count()>1).Select(g=>g.Key).ToList().Contains(x.T分机));我自己需要从字符串列表中查找和删除重复项我首先搜索重复项的索引,然后使用LINQ在不更改原始列表的情况下在功能上过滤列表:WhatisthemostelegantwaytofindduplicateitemindexesinWhat就是分享的全部内容,如果对大家有用,需要了解更多C#学习教程,希望大家多多关注——publicstaticIEnumerableRemoveDuplicates(IEnumerableitems){varduplicateIndexes=items.Select((item,index)=>new{item,index}).GroupBy(g=>g.item).Where(g=>g.Count()>1).SelectMany(g=>g.Skip(1),(g,项目)=>项目.索引);返回items.Where((item,index)=>!duplicateIndexes.Contains(index));}本文收集自网络,不代表立场,如有侵权请点右联系管理员删除。如需转载请注明出处:
