How to prevent a System.IndexOutOfRangeException exception in LINQ WHERE?

I came across this exception when I use String.Split with random strings.

 List<string> linhas = new List<string>(); linhas.Add("123;abc"); linhas.Add("456;def"); linhas.Add("789;ghi"); linhas.Add("chocolate"); var novas = linhas.Where(l => l.ToString().Split(';')[1]=="def"); 
+5
source share
2 answers

The last line of "chocolate" does not contain ";" , so String.Split returns an array with a single string of "chocolate" . This is why you get an exception if you try to access the second.

You can use ElementAtOrDefault , which returns null for strings:

 var novas = linhas.Where(l => l.Split(';').ElementAtOrDefault(1) == "def"); 

Longer approach using anonymous type:

 var novas = linhas .Select(l => new { Line = l, Split = l.Split(';') }) .Where(x => x.Split.Length >= 2 && x.Split[1] == "def") .Select(x => x.Line); 
+12
source

I’ll talk a little about Tim’s answer and show you a way to do a few extra things in your LINQ queries.

You can expand the logic inside your Where clause to perform some additional processes that can make your code more readable. That would be good for something small:

 var novas = linhas.Where(l => { var parts = l.Split(':'); return parts.Length > 1 ? parts[1] == "def" : false; }); 

If you need multiple statements, you can wrap the body of your sentence in braces, but then you need the return keyword.

Alternatively, if you have a lot of information that will do something inline as unreadable, you can also use a separate method in your request.

 public void FindTheStringImLookingFor() { var linhas = new List<string>(); linhas.Add("123;abc"); linhas.Add("456;def"); linhas.Add("789;ghi"); linhas.Add("chocolate"); var words = linhas.Where(GetTheStringIWant); } private bool GetTheStringIWant(string s) { var parts = s.Split(':'); // Do a lot of other operations that take a few lines. return parts.Length > 1 ? parts[1] == "def" : false; } 
+1
source

Source: https://habr.com/ru/post/1241244/


All Articles