0

How to remove my value in String Array and how i can rearrange

public string[] selNames = new string[5];
selNames[0]="AA";
selNames[1]="BB";
selNames[2]="CC";
selNames[3]="DD";
selNames[4]="EE";

In certain Conditaion i need to Check for the existing value and i want to remove it from my collection, How i can do it.

i tried like below, but i cannot, it returns true, but how to make that index value to null

If(selNames .Contains("CC").ToString()==true)

{ // how to make that index null which contains the "CC"; and i need to rearrage the array }

2
  • 1
    Can you use another data structure instead of array, e.g. Dictionary<> bit.ly/9IhY4j or HashSet<> bit.ly/c4GMUu? It provides both features (quick search and removing) by default. Commented Oct 26, 2010 at 7:19
  • 1
    @ Nick Martyshchenko :(+1) i think Generic types are more flexible to handle. Commented Oct 26, 2010 at 7:33

2 Answers 2

3

You can do following.

var newArray = selNames.Where(s => s != "CC").ToArray();

where s is the arg of the Func<TSource, bool> delegate TSource is string in your case. So it will compare each string in array and return all which is not "СС"

here is a link to msdn

Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't this be enough? var newArray = selNames.Where(s => s != "CC").ToArray();
@deep : s represents the current item in the array. just like X in foreach(String X in selNames )
2

You can use the 'List< T >' for checking the existing values and also can remove the item from the list and also can arrange the list. The following is the code snippet:

 List<string> list = new List<string>();
 list.Add("AA");
 list.Add("BB");
 list.Add("CC");
 list.Add("DD");
 list.Add("EE");
 list.Add("FF");
 list.Add("GG");
 list.Add("HH");
 list.Add("II");

 MessageBox.Show(list.Count.ToString());
 list.Remove("CC");
 MessageBox.Show(list.Count.ToString());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.