c# 把List中重復的資料去掉


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

class Program
{
    static void Main()
    {
 // List with duplicate elements.
 List<int> list = new List<int>();
 list.Add(1);
 list.Add(2);
 list.Add(3);
 list.Add(3);
 list.Add(4);
 list.Add(4);
 list.Add(4);

 foreach (int value in list)
 {
     Console.WriteLine("Before: {0}", value);
 }

 // Get distinct elements and convert into a list again.
 List<int> distinct = list.Distinct().ToList();

 foreach (int value in distinct)
 {
     Console.WriteLine("After: {0}", value);
 }
    }
}

Output

Before: 1
Before: 2
Before: 3
Before: 3
Before: 4
Before: 4
Before: 4
After: 1
After: 2
After: 3
After: 4

留言

這個網誌中的熱門文章

[心得] 圖解 微分、積分生活中的微積分-第一章

Objective-C的數學運算函式