• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 152
  • Last Modified:

ASP.NET C# - Remove item from array by value

Using ASP.NET/C#/LINQ, how can I remove "Bananas" from this array?
string Fruit_List = "Apples,Oranges,Grapes,Bananas,Peaches,Mangos";
string[] Fruits = Fruit_List.Split(',');

Open in new window

0
skij
Asked:
skij
1 Solution
 
Lokesh B RDeveloperCommented:
Hi,

Method 1

              string Fruit_List = "Apples,Oranges,Grapes,Bananas,Peaches,Mangos";
                string[] Fruits = Fruit_List.Split(',');
              
                string fruit = "Bananas";
                int index = Array.IndexOf(Fruits, fruit);
                if (index != -1)
                {
                     Fruits = Fruits.Where((val, idx) => idx != index).ToArray();
                }

Open in new window


Method 2

string Fruit_List = "Apples,Oranges,Grapes,Bananas,Peaches,Mangos";
                string[] Fruits = Fruit_List.Split(',');
                
                string fruit = "Bananas";
                Fruits = Fruits.Except(new string[] { fruit }).ToArray();

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now