Add elements into an array when the element doesnt exist
I habe a sentence:
string x = "This is a first string, this is a second string.";
When add every word into an array
string[] words = x.Trim().Split(new char[] { ' ' });
What do I have to do to add only unique words into 开发者_如何学运维the array ?
Use Linq.
Also, since Split takes a params array, you don't need the new char[] part.
string[] words = x.Trim().Split(' ').Distinct().ToArray();
Use
string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();
You have to do is:
string[] words = x.Trim().Split(new char[] { ' ' }).Distinct().ToArray();
Before adding the string to array, you could traverse the array to see if word already exists.
For example:
List<string> arrayStr = new List<string>();
Before adding, you could do
if(arrayStr.Contains(abc))
MessageBox.Show("Word already exists");
else
arrayStr.Add(abc);
hope this helps
精彩评论