Click here to Skip to main content
15,304,276 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys,
I have a list containing multiple values​​.
C#
List <string> yourList = new List () {"012345", "032165", "211458", "214563", "098796", "574623", "894235", "3135698"};

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:
C#
List <string> firstDigits = yourList.Select (x => x.Substring (0, 1)). ToList ();

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
Posted
Updated 28-Aug-13 2:22am
v2

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

Hope this helps.
   
v2
Comments
fasher_the_one 28-Aug-13 9:10am
   
thanks again ProgramFox. was exactly what I needed.
came another question, I take to get here as soon as it is all about manipulating lists.
  I need to do various manipulations, but first of all I need to do this check if the list has more than one element. If there is only one element in the list, I need to display a warning of this item.
Thomas Daniels 28-Aug-13 10:37am
   
To check whether the list has more than one element, try this:

if (yourList.Count > 1)
{
// list has more than 1 elements
}
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 ();
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900