C#重复数据删除列表基于拆分

2 c#

我很难根据特定的分隔符重复列表.

例如,我有4个字符串,如下所示:

苹果|梨|水果|篮
橙|芒果|水果|乌龟
紫|红|黑|绿
英雄|托尔|铁人|绿巨人

在这个例子中,我希望我的列表在第3列中只有唯一值,因此它会产生一个如下所示的List,

苹果|梨子|水果|篮子
紫色|红色|黑色|绿色
英雄|托尔|铁人|绿巨人

在上面的示例中,我将摆脱第2行,因为第1行在第3列中具有相同的结果.任何帮助都会很棒,在C#中重复数据删除很难.

我是如何测试的:

    static void Main(string[] args)
    {
        BeginListSet = new List<string>();
        startHashSet();
    }


    public static List<string> BeginListSet { get; set; }

    public static void startHashSet()
    {
        string[] BeginFileLine = File.ReadAllLines(@"C:\testit.txt");
        foreach (string begLine in BeginFileLine)
        {

            BeginListSet.Add(begLine);
        }

    }

    public static IEnumerable<string> Dedupe(IEnumerable<string> list, char seperator, int keyIndex)
    {
        var hashset = new HashSet<string>();
        foreach (string item in list)
        {
            var array = item.Split(seperator);
            if (hashset.Add(array[keyIndex]))
                yield return item;
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 6

这样的事情对你有用

static IEnumerable<string> Dedupe(this IEnumerable<string> input, char seperator, int keyIndex)
{
    var hashset = new HashSet<string>();
    foreach (string item in input)
    {
        var array = item.Split(seperator);
        if (hashset.Add(array[keyIndex]))
            yield return item;
    }
}
Run Code Online (Sandbox Code Playgroud)

...

var list = new string[] 
{
    "apple|pear|fruit|basket", 
    "orange|mango|fruit|turtle",
    "purple|red|black|green",
    "hero|thor|ironman|hulk"
};

foreach (string item in list.Dedupe('|', 2))
    Console.WriteLine(item);
Run Code Online (Sandbox Code Playgroud)

编辑:与Lambda的链接问题Distinct()中,Jon Skeet以DistinctBy自定义方法的形式以更好的方式呈现了这个想法.虽然相似,但它比这里提出的想法更容易重复使用.

使用他的方法,你可以写

var deduped = list.DistinctBy(item => item.Split('|')[2]);
Run Code Online (Sandbox Code Playgroud)

您可以稍后重复使用相同的方法,通过可能的另一种类型的键"重复删除"另一种不同类型的对象列表.