开发者

Linq or Lambda Expression for returning comma separated values

开发者 https://www.devze.com 2023-01-27 00:15 出处:网络
How can I get a list of comma separated values, like so: CategoryName-ProductName1,ProductName2,etc This code returns Product names that are comma-separated, but at the begening of the series I wan

How can I get a list of comma separated values, like so:

CategoryName-ProductName1,ProductName2,etc

This code returns Product names that are comma-separated, but at the begening of the series I want the category name to appear and the preceding product names:

var result = from Cats in Categories
    where Cats.Id == 39
    select new { 
        Products = Cats.Products, 
        Cats = Cats
    }.
    Products.
    Select(Products => Products.Name).
   开发者_如何学Python Aggregate((Items, Item) => Items + "," + Item);


You can try:

var result = from cat in Categories
             where cat.Id == 39
             select cat.Name + "-" + String.Join(",",
                 cat.Products.Select(product => product.Name));


Try:

string result = Categories.Where(y => y.Id == 39).
                Select(y => y.Name + String.Join(",", y.Products.Select(x => x.Name)));

I haven't tried it myself but it should work :)


Categories
    .Where(c => c.Id == 39)
    .Select(c => c.Name + "-" + c.Products.Select(p => p.Name).Aggregate((acc,p) => acc + "," + p))


Several options here. My take would be to split it in two:

var cat = Categories.Where(cat => cat.Id == 39);
var result = string.Format("{0}-{1}",
                  cat.Name,
                  cat.Products.Aggregate((list, product) => list + "," + product.Name));
0

精彩评论

暂无评论...
验证码 换一张
取 消