2

I have a list of file names (targetFileList), some of which are duplicates (ex. I have two files called m4.txt). The following statement finds the duplicated filenames and adds them to another list (currentTargetFiles):

currentTargetFiles = targetFileList.FindAll(item => item == baselineFilename);

As is, this line is returning a list of strings (filenames), which is good, but I also need their index value. Is there some way to modify it so that it also returns the indices of the files?

4

4 回答 4

7

好吧,这是我对“查找重复名称及其索引”的回答。它可能不完全适合提出的问题,因为没有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

当然,必须正确使用提供的结果——这取决于最终必须做什么。

于 2013-03-18T19:27:48.640 回答
2

您可以通过以下方式选择所有项目及其索引:

tempList = targetFileList.Select((item, index) => 
    new { Value = item, Index = index }).Where(x => x.Value == baselineFilename);

现在,您可以使用以下命令创建名称列表和相应索引:

var indexes = tempList.Select(x => x.Index).ToList();

和价值观:

currentTargetFiles = tempList.Select(x => x.Value).ToList();

然后,indexes[0]将保存 的列表索引currentTargetFiles[0]

于 2013-03-18T18:37:56.370 回答
2
int i = -1;
var currentTargetFiles = targetFileList.Select(x => new
                                                        {
                                                           Value = x,
                                                           Index = i++
                                                        })
                                       .Where(x => x.Value == baselineFilename);
于 2013-03-18T18:22:15.887 回答
1

linq 是必需的吗?

传统的 for 循环和字典就可以了:

Dictionary<int, string> currentTargetFiles = new Dictionary<int, string>();
for (int i = 0; i < targetFileList.Count; ++i)
    if(targetFileList[i] == baselineFilename)
        currentTargetFiles.Add(i, targetFileList[i]);

PS:

刚刚意识到您正在比较一个确切的字符串 ( item == baselineFilename)。

如果是这种情况,您甚至不需要为每个索引保留每个值(因为所有值都相同)。

List<int> currentTargetFilesIndices = new List<int>();
for (int i = 0; i < targetFileList.Count; ++i)
    if(targetFileList[i] == baselineFilename)
        currentTargetFiles.Add(i);
于 2013-03-18T18:43:18.467 回答