问题描述
大家好,
我有一个包含多个值的列表。
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
推荐答案
List<string> firstDigits = yourList.Select(x => x.Substring (0, 1)).Distinct().ToList();
希望这会有所帮助。
Hope this helps.
这篇关于在C#中复制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!