簡體   English   中英

從列表中刪除重復的元素<String>

[英]Remove duplicated elements from a List<String>

我想從列表中刪除重復的元素。 列表的一些元素如下所示:

Book  23
Book  22
Book  19
Notebook 22
Notebook 19
Pen 23
Pen 22
Pen 19

為了擺脫重復的元素,我已經完成了這個:

List<String> nodup = dup.Distinct().ToList();

我想保留在列表中

Book 23
Notebook 22
Pen 23

我怎樣才能做到這一點 ?

你可以做些喜歡的事

string firstElement = dup.Distinct().ToList().First();

並根據需要將其添加到另一個列表中。

它不是100%清楚你想要的 - 但是......

如果要保留列表中的“最大”數字,可以執行以下操作:

List<string> noDup = dup.Select(s => s.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
        .Select(p => new { Name=p[0], Val=int.Parse(p[1]) })
        .GroupBy(p => p.Name)
        .Select(g => string.Join(" ", g.Key, g.Max().ToString()))
        .ToList();

這將通過將數字部分解析為數字,獲取每個項目的最大值,並按照您指定的方式創建輸出字符串來轉換List<string>

您可以將LINQ與一些String操作結合使用,按名稱和MAX(Number)對所有項目進行分組:

var q = from str in list
        let Parts = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        let item = Parts[ 0 ]
        let num = int.Parse(Parts[ 1 ])
        group new  { Name = item, Number = num } by item into Grp
        select new {
            Name  = Grp.Key,
            Value = Grp.Max(i => i.Number).ToString()
        };

var highestGroups = q.Select(g => 
    String.Format("{0} {1}", g.Name, g.Value)).ToList();

(與Reed的方法相同,但在查詢語法中,我的腦海中更易讀)

編輯 :我無法重現您的評論它不起作用,這里是示例數據:

List<String> list = new List<String>();
list.Add("Book  23");
list.Add("Book  22");
list.Add("Book 19");
list.Add("Notebook  23");
list.Add("Notebook  22");
list.Add("Notebook  19");
list.Add("Pen  23");
list.Add("Pen  22");
list.Add("Pen  19");
list.Add("sheet 3");

var q = from str in list
        let Parts = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
        let item = Parts[ 0 ]
        let num = int.Parse(Parts[ 1 ])
        group new  { Name = item, Number = num } by item into Grp
        select new {
            Name  = Grp.Key,
            Value = Grp.Max(i => i.Number).ToString()
        };

var highestGroups = q.Select(g => String.Format("{0} {1}", g.Name, g.Value));
MessageBox.Show(String.Join(Environment.NewLine, highestGroups));

結果:

Book 23
Notebook 23
Pen 23
sheet 3

您可能希望將自定義比較器添加為參數,如MSDN上的示例所示

在這個例子中,我假設Foo是一個有兩個成員的類。

class Program
{
    static void Main(string[] args)
    {
        var list = new List<Foo>()
        {
            new Foo("Book", 23),
            new Foo("Book", 22),
            new Foo("Book", 19)
        };

        foreach(var element in list.Distinct(new Comparer()))
        {
            Console.WriteLine(element.Type + " " + element.Value);
        }
    }
}

public class Foo
{
    public Foo(string type, int value)
    {
        this.Type = type;
        this.Value = value;
    }

    public string Type { get; private set; }

    public int Value { get; private set; }
}

public class Comparer : IEqualityComparer<Foo>
{
    public bool Equals(Foo x, Foo y)
    {
        if(x == null || y == null)
            return x == y;
        else
            return x.Type == y.Type;
    }

    public int GetHashCode(Foo obj)
    {
        return obj.Type.GetHashCode();
    }
}

這適用於IList ,假設我們需要每個第一個項目 ,而不是具有最高編號的項目。 請注意不同的集合類型(如ICollectionIEnumerable ),因為它們不保證您有任何訂單。 因此,任何Foo可能在Distinct之后保留。

您還可以覆蓋Foo EqualsGetHashCode ,而不是使用自定義IEqualityComparer 但是,我實際上並不建議將其用於本地區域。 您的類的消費者可能無法識別具有相同Value Type兩個實例始終相等,無論其Value如何。

有點老式,但它應該工作,如果我理解正確

    Dictionary<string,int> dict=new Dictionary<string,int>();

    //Split accepts 1 character ,assume each line containes key value pair seperated with spaces and not containing whitespaces
    input=input.Replace("\r\n","\n");
    string[] lines=input.Split('\n');

    //break to categories and find largest number at each 
    foreach(line in lines)
    {
        string parts[]=line.Split(' ');
        string key=parts[0].Trim();
        int value=Convert.ToInt32(parts[1].Trim());

        if (dict.ContainsKey(key))
        {
            dict.Add(key, value);
        }
        else
        {
            if (dict[key]<value)
            {
                    dict[key]=value;
            }
        }

    }


    //do somethig with dict 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM