如何从列表中访问不同的项目? [英] How can I access different item from a list?

查看:72
本文介绍了如何从列表中访问不同的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



像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


这篇关于如何从列表中访问不同的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆