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 am not able to get all the records in tst, it is giving me records only for the last value in array.

So if my array contains 1,2,3,4 I am getting records only for the 4. Whereas i need all the result for 1,2,3 and 4 get appended in tst.

Any help will be appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Concat doesn’t modify anything – it returns a new sequence, which you’re currently ignoring.

However, rather than using Concat, you should just use SelectMany to flatten 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 into a List<short> and then you can do one query:

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

Method 2

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

Either use in your else :

tst = tst.Concat(...)

Or Change your Enumerable into 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;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x