2

I have a table in sql server with the following structure.

tblFruit:

╔════╦══════════════╦══════╗
║ Id ║  Fruit       ║ Color║
╠════╬══════════════╬══════╣
║  1 ║ Peacock      ║ Red  ║
║  2 ║ Hawk         ║ Green║
║  3 ║ Lion         ║ Red  ║
║  4 ║ Lizard       ║ Red  ║
╚════╩══════════════╩══════╝ 

This is my query in LINQ :

db.Fruits.Where(r => r.Color == "Red")
         .Select(r => r.Fruit)
         .ToList()

I will get 3 rows of result from the table.

However I need the result to be Peacock,Lion,Lizard. Is there a way of getting this from LINQ or should I use a foreach loop and concatenate manually?

0

1 Answer 1

3

You can use String.join():

var fruits = db.Fruits.Where(r => r.Color == "Red")
                      .Select(r => r.Fruit)
                      .AsEnumerable();

Console.WriteLine(String.join(",", fruits));
Sign up to request clarification or add additional context in comments.

5 Comments

Does String.Join work with Linq to Entities?
@maccettura Sorry, javascript is starting to slowly consume my soul
No. In EF6 this will be translated into SQL and string.Join is not supported. You have to use fruits.AsEnumerable().
@GertArnold exactly what I was trying to say, thanks for the more decent explanation :)
@GertArnold Yes, you are correct. You will need to involve .ToList(), .ToArray(), or .AsEnumerable(); before working with the data, to avoid the magic behind the scenes of the IQueryable interface.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.