用于返回逗号分隔值的Linq或Lambda表达式

时间:2010-11-24 19:24:45

标签: c# linq lambda

如何获取逗号分隔值列表,如下所示:

CategoryName-ProductName1,ProductName2,etc

此代码返回以逗号分隔的产品名称,但在系列的创建中,我希望显示类别名称和前面的产品名称:

var result = from Cats in Categories
    where Cats.Id == 39
    select new { 
        Products = Cats.Products, 
        Cats = Cats
    }.
    Products.
    Select(Products => Products.Name).
    Aggregate((Items, Item) => Items + "," + Item);

4 个答案:

答案 0 :(得分:4)

您可以尝试:

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

答案 1 :(得分:2)

尝试:

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

我自己没有尝试过,但它应该有效:)

答案 2 :(得分:1)

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

答案 3 :(得分:0)

这里有几种选择。我的看法是把它分成两部分:

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