DKFrederik DKFrederik - 2 months ago 6
C# Question

want to remove "0" at index 0 in a list but not 10,20,30..... C#

my code
...

List<int> a = new List<int>();
List<int> b = new List<int>();


...

some boxes for input

...

var match = a.Intersect(b);
string output = string.Join(",", match);
foreach (var x in output)
{
label.Text += Regex.Replace(Convert.ToString(x), "[0]", "");
}


but this deletes all 0's
if I enter 0, 10, 100
I only wanna delete the first 0 (index0 as List is sorted) but I can't make an expression saying that it should remove index0 all the time, because i depends on, if the users enter a 0... so it should look for a 0 at first index and (only) if its there... remove it.

I can't wrap my head around this.

Thanks in advance

Answer

Don't know why you need regex and the loop over the chars. Here are 3 ways of doing so:

List<int> a = new List<int> { 0, 10, 20, 5 };
List<int> b = new List<int> { 0, 10, 20 };

//Option 1 - .Remove() on one of the lists
a.Remove(0);
var matches = a.Intersect(b);

//Option 2 - .Remove() on intersection
var matches = a.Intersect(b).ToList();
matches.Remove(0);

//Option 3 - .Where()
var matches = a.Where(item => item != 0)
               .Intersect(b);

var text = string.Join(",", matches); //For both ways: 10,20