100

I have a class in my application

public class ProductInfo
{
  public int ProductId {get;set;}
  public int ProductType{get;set;}
}

I want to write a linq query which can return me a list of ProductIds in a comma separated format where ProductType is equal to certain number ?

I tried using string.join with my Linq statement but it didn't seem to work.

1 Answer 1

288
var s = string.Join(",", products.Where(p => p.ProductType == someType)
                                 .Select(p => p.ProductId.ToString()));
Sign up to request clarification or add additional context in comments.

5 Comments

Not even 1 minute completed :)
@SriramSakthivel I know many people here always try to answer as quickly as possible :), I'm just a learner compared to them :)
How would you select multiple columns?
@DougDexter not sure what you meant in this context. The OP's question is fairly specific about obtaining a string with some values separated by commas. So the result in Select should be a string or otherwise the ToString() on each item will be called to get a string. If you select multiple properties (as understood by you as columns), those properties still need to be combined somehow to make a string. So that's the unclear point. It depends more on how you want the data to be shaped.
@jazzBox to select multiple columns, try the following: string.Join(",", products.Where(p => p.ProductType == someType) .Select(p => $"ID: {p.ProductId.ToString()} Name: {p.ProductName.ToString()}"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.