c# - 如何获取列表中重复项的值和索引?

标签 c# list duplicates

我有一个文件名列表 (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/

相关文章:

c# - 通过接口(interface)创建假对象

python - 如何限制每个循环读取带有引号的多个字符串作为Python中的单个字符串?

python - Pandas Dataframe 合并而不复制任何一方?

ios - 如何删除 CoreData 中的重复条目?

dataframe - Spark 数据帧覆盖会创建重复项

c# - 在 ASP.NET Core Web API 应用程序中禁用 Ctrl+C 关闭

c# - gRPC 在 protobuf 中使用列表

java - `Java` `List` 方法 `size` 是如何工作的?

c# - 实现一维碰撞检测的最佳方法是什么?

architecture - 数据访问层 : Exposing List<>: bad idea?