如何使用linq比较和替换一个列表中的重复字符串

时间:2014-12-19 02:42:08

标签: c# linq

我想检查删除;拆分的字符串中的副本,但我不知道下一步怎么办 我的代码是这样的:

    string str = "PORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR;/n/nabcdef1234;/n/nabcdef1234";
    List<string> unitList = new List<string>();

    foreach (string s in str.Replace("/n","").Split(';'))
    {
        unitList.Add(s);
    }

    if ((unitList.Distinct()).Count() == 1)
        Label1.Text=unitList.FirstOrDefault();
    else
    {
       //return more than 1 ,remove duplicate
       //replace duplicate by "-" or ""
    }

我的输出想要:"PORTION G ON GROUND FLOOR;/n/n-;/n/nabcdef1234;/n/n-"

我发现如果我使用string []数组而不是List,返回(unitList.Distinct()).Count()是2而不是1,我想知道是否有错。
这是我的代码:

    string str = "PORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR";

    string[] unitList = new string[10];
    int i=0;
    foreach (string s in str.Replace("/n","").Split(';'))
    {

        unitList[i]=s;
            i++;
    }

我很高兴并感谢任何人帮助我解决它!

3 个答案:

答案 0 :(得分:1)

 string str = "PORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR;/n/nabcdef1234;/n/nabcdef1234";

            var list = str.Replace("/n", "").Split(';');
            var result = (from s in list
                group s by s
                into g
                select g.First()).ToList();

分割后,您可以按照数组中的字符串进行分组,然后选择第一个字符串。

答案 1 :(得分:1)

这是解决您问题的方法:

 string str = "PORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR;/n/nabcdef1234;/n/nabcdef1234";
 List<string> selected=new List<string>();
 var result = str.Split(';').Select(s =>
                                       {
                                         var word = s.Replace("/n", "");
                                         if (selected.Contains(word))
                                         {
                                           return s.Replace(word,"")+"-";
                                         }
                                         else
                                         {
                                           selected.Add(word);
                                           return s;
                                         }
                                        }).Aggregate<string, string>(null, (current, item) => current + item);

此代码返回您期望的字符串。

但是如果你想要没有重复的单词列表,这是获得它的另一种方法:

var list = str.Split(';').ToLookup(s => s.Replace("/n", "")).Select(e=>e.Key);

答案 2 :(得分:0)

string str = "PORTION G ON GROUND FLOOR;/n/nPORTION G ON GROUND FLOOR;/n/nabcdef1234;/n/nabcdef1234";
            var temp =  str.Replace("/n", string.Empty).Split(';').Distinct();
            var result = string.Join("/n", temp);

希望你期待同样的事情