Enumerable.Concat not working

Below is the code:

string[] values = Acode.Split(','); IEnumerable<Test> tst = null; foreach (string a in values) { if (tst== null) tst = entities.Test.Where(t=> (t.TCode == Convert.ToInt16(a))); else tst.Concat(entities.Test.Where(g => (g.TCode == Convert.ToInt16(a)))); } return tst.ToList(); 

I can not get all the entries in tst, it gives me entries only for the last value in the array.

So, if my array contains 1,2,3,4, I only get entries for 4. If I need the whole result for 1,2,3 and 4, add it to tst.

Any help would be appreciated.

+6
source share
2 answers

Concat doesn't change anything - it returns a new sequence that you are currently ignoring.

However, instead of using Concat , you should simply use SelectMany to smooth the sequence:

 string[] values = Acode.Split(','); return values.SelectMany(a => entities.Test.Where(t => t.TCode == Convert.ToInt16(a))) .ToList(); 

Or more efficiently convert values to List<short> , and then you can make one request:

 List<short> values = Acode.Split(',').Select(x => short.Parse(x)).ToList(); return entities.Test.Where(t => values.Contains(t.TCode)).ToList(); 
+10
source

This is because Concat will return a new instance of your enumerable.

Or use in your friend:

tst = tst.Concat(...)

Or Change your Enumerable to List from the beginning:

 string[] values = Acode.Split(','); List<Test> tst= new List<Test>; foreach (string a in values) { tst.AddRange(entities.Test.Where(g => (g.TCode == Convert.ToInt16(a)))); } return tst; 
+4
source

All Articles