0

Give the string Metal_In I have to extract the Metal part

I'm doing the following now:

DropDownList ddl = ctrl as DropDownList;
if(ddl != null)
{
    ddl.ID = ddl.ID.Split('_')[1].ToString();   
}
1
  • I think I managed to extract what the OP meant with my last edit. Commented Nov 2, 2012 at 7:28

4 Answers 4

3

instead of index 1 use index 0 (it can be done in a better way). Also you don't need ToString at the end as it is already a string.

dl.ID = ddl.ID.Split('_')[0].ToString();

You may check for array length before using index and .ToString

string[] tempArray = ddl.ID.Split('_');
if(tempArray.Length > 0)
    ddl.ID = tempArray[0];

ddl.ID.Split('_')[1] will give you the 2nd part of the string which is In. Remember the array index starts with 0

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

Comments

1

With the string Metal_In, call Split ( broken out example below ).

string[] elems = ddl.ID.Split('_');

// elems contains two elements
// 0 - Metal
// 1 - in

To get the value of Metal, use subscript 0 to get the first element.

string firstPart = elems[0];

Comments

0

Since it can be assumed that Metal word exists in original string,

var item = ddl.Id.Split('_)[0]

Otherwise go with Habib's answer.

Comments

0

You can use FirstOrDefault, it will handle the array issues.

ddl.ID = ddl.ID.Split('_').FirstOrDefault();

It will return null in case of empty array.

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.