如何从列表中访问不同的项目?

问题描述:

我有一个列表,其中所有项目都是字符串。



像ab,bc,ab,ts,ab,bc,ts,op



从这里你可以看到,不同名单上的字符串项目是相同的。



我想要从这个列表中只获取一次所有项目。



喜欢来自给定列表的ab,bc,ts,op。



如何从列表中获取不同项目的所有项目?

I have a list where all items are string.

Like ab,bc,ab,ts,ab,bc,ts,op

From here you can see, there is a lot of string item in different places of list are same.

I want get all the items only for once from this list.

Like ab,bc,ts,op from from the given list.

how can i get different item all items from a list?

您可以使用 Distinct 收集方法。

区别 删除集合中的所有重复元素。它只返回不同的元素。 System.Linq命名空间提供此扩展方法。

You could use Distinct method of collection.
Distinct removes all duplicate elements in a collection. It returns only the distinct elements. The System.Linq namespace provides this extension method.
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);
	}
    }



希望这会对你有所帮助:)

-KR


Hope this would help you :)
-KR