我有一个文件名列表 (targetFileList),其中一些是重复的(例如,我有两个名为 m4.txt 的文件)。以下语句找到重复的文件名并将它们添加到另一个列表 (currentTargetFiles):
currentTargetFiles = targetFileList.FindAll(item => item == baselineFilename);
照原样,这一行返回一个字符串列表(文件名),这很好,但我还需要它们的索引值。有没有办法修改它以便它也返回文件的索引?
最佳答案
好吧,这是我对“查找重复名称及其索引”的回答。它可能不完全适合所提出的问题,因为没有考虑 baselineFilename
- 但其他答案涵盖了这一点。 YMMV.
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
当然,提供的结果必须正确使用——这取决于最终必须做什么。
关于c# - 如何获取列表中重复项的值和索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15484048/