在C#中复制列表 [英] Copying lists in C #

查看:82
本文介绍了在C#中复制列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个包含多个值的列表。

Hello guys,
I have a list containing multiple values​​.

List <string> yourList = new List () {"012345", "032165", "211458", "214563", "098796", "574623", "894235", "3135698"};



如你所见,每个数字可以是0-9。



现在我想要的是创建一个新列表,首先只选择列表中每个元素的第一个数字。我的新列表看起来像这样: [0,0,2,2,0,5,8,3]



我学到了在这个论坛上,这样做:


as you can see, each digit can be 0-9.

Now what I want is to create a new list, first picking only the first digit of each element of the list. my new list would look like this: [0, 0, 2, 2, 0, 5, 8, 3]

I learned on this forum how to do this, this way:

List <string> firstDigits = yourList.Select (x => x.Substring (0, 1)). ToList ();



现在我的问题,我想知道是否必须创建这个新列表而不重复数字。例如,我添加了一个数字2,并再次发现2不会被添加到同一个列表中。然后列表只会这样: [0,2,5,8,3] 这是主列表中每个元素的第一个数字,但没有重复。



是否必须这样做?我很感激帮助


Now comes my question, I wonder if I have to create this new list without repeating digits. For example, I've added a number 2 and again find the "2" would not be added to the same list. then the list would only like this: [0, 2, 5, 8, 3] which are the first digit of each element in the main list, but without repetition.

does it have to do this? I appreciate the help

推荐答案

看起来你想得到不同的值。试试这个:

It looks like you want to get distinct values. Try this:
List<string> firstDigits = yourList.Select(x => x.Substring (0, 1)).Distinct().ToList();



希望这会有所帮助。


Hope this helps.


我不在带有visual studio的电脑附近,所以这个解决方案可能无效,但试试这个



List< string> firstDigits = yourList..GroupBy(x => x.Substring(0,1))。选择(x => x.Substring(0,1))。 ToList();
I'm not near a PC with visual studio so this solution may not work, but try this

List <string> firstDigits = yourList..GroupBy(x => x.Substring(0,1)).Select (x => x.Substring (0, 1)). ToList ();


这篇关于在C#中复制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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