use*_*189 2 c# list duplicates
我有一个文件名列表(targetFileList),其中一些是重复的(例如,我有两个名为m4.txt的文件).以下语句查找重复的文件名,并将它们添加到另一个列表(currentTargetFiles):
currentTargetFiles = targetFileList.FindAll(item => item == baselineFilename);
原样,这一行返回一个字符串列表(文件名),这很好,但我也需要它们的索引值.有没有办法修改它,以便它还返回文件的索引?
小智 7
好吧,这是我的答案"找到重复的名称及其索引".它可能不完全符合所提出的问题,因为没有baselineFilename考虑 - 但其他答案也涵盖了这一点.因人而异.
var names = new [] {"a", "a", "c", "b", "a", "b"};
var duplicatesWithIndices = names
// Associate each name/value with an index
.Select((Name, Index) => new { Name, Index })
// Group according to name
.GroupBy(x => x.Name)
// Only care about Name -> {Index1, Index2, ..}
.Select(xg => new {
Name = xg.Key,
Indices = xg.Select(x => x.Index)
})
// And groups with more than one index represent a duplicate key
.Where(x => x.Indices.Count() > 1);
// Now, duplicatesWithIndices is typed like:
// IEnumerable<{Name:string,Indices:IEnumerable<int>}>
// Let's say we print out the duplicates (the ToArray is for .NET 3.5):
foreach (var g in duplicatesWithIndices) {
Console.WriteLine("Have duplicate " + g.Name + " with indices " +
string.Join(",", g.Indices.ToArray()));
}
// The output for the above input is:
// > Have duplicate a with indices 0,1,4
// > Have duplicate b with indices 3,5
Run Code Online (Sandbox Code Playgroud)
当然,必须正确使用提供的结果- 这取决于最终必须完成的工作.