【问题标题】:LINQ Find String Duplicates in ListLINQ 在列表中查找重复的字符串
【发布时间】:2019-04-30 23:31:57
【问题描述】:

我试图防止列表中的名称重复,但到目前为止没有运气。

我有一个条目列表,每个条目都有一个名称(例如条目:file”、“file1”、“someFile”、“anotherFile”)。每当我创建新条目时,我都会将其添加到条目列表中。但我不想添加具有相同名称的新条目。

我有一个刚刚创建的文件(例如名称:文件” )。
我如何找到所有重复的名称并在末尾设置如下:“file2”?
对不起,如果问题有点含糊。

我尝试使用 LINQRegex,但我对这些东西有点陌生,所以不确定我在做什么..

【问题讨论】:

  • 你至少需要展示一些你尝试过的代码......考虑List<string>.Contains
  • 我没有太多要展示的东西,我只是在网上浏览了有关 LINQ 和 Regex 的信息,但我没有尝试任何方法,所以最后我只有一堆凌乱且无意义的代码。 .
  • 在问题中添加您试图为我们提供线索的任何内容。谢谢

标签: regex string linq filter duplicates


【解决方案1】:

根据您发布的问题,一个带有 if-else 条件的简单程序可以解决您的问题:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;


public class Program
{
    public static void Main()
    {
        string[] entries = new []{"file", "file1", "someFile", "anotherFile", "file", "someFile", "file"};
        List<string> curatedEntries = new List<string>();

        foreach(string e in entries)
        {
            int index = 0;
            string entry = e;
            Check:
            if(CheckExists(curatedEntries, entry)){
                index++;
                entry = e + index;
                goto Check;
            }

            curatedEntries.Add(entry);
        }
        curatedEntries.ForEach(x=>Console.WriteLine(x));
    }

    public static bool CheckExists(List<string> lst,string e)
    {
        return lst.Any(x=>x.Equals(e));
    }
}

这是小提琴:https://dotnetfiddle.net/fdSClH

【讨论】:

    猜你喜欢
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多