鉴于此课程:
public class Article
{
public string Name { get; set; }
public string Colour { get; set; }
}
假设我有以下List<Article>
,其中一些文章包含以逗号分隔的名称:
var list = new List<Article>
{
new Article { Name = "Article1, Article2, Article3", Colour = "Red" },
new Article { Name = "Article4, Article5, Article6", Colour = "Blue" },
}
在一个Linq
语句中,是否有办法获取一个列表,其中每个逗号分隔的名称都成为单独的文章?
var list = new List<Article>
{
new Article { Name = "Article1", Colour = "Red" },
new Article { Name = "Article2", Colour = "Red" },
new Article { Name = "Article3", Colour = "Red" },
new Article { Name = "Article4", Colour = "Blue" },
new Article { Name = "Article5", Colour = "Blue" },
new Article { Name = "Article6", Colour = "Blue" },
}
答案 0 :(得分:9)
您可以使用SelectMany
:
var res = list.SelectMany(
art => art.Name.Split(',').Select(n =>
new Article {
Name = n.Trim()
, Colour = art.Colour
}
)
);
我希望有一种方法可以节省我新的对象,因为我的班级[...]有两个以上的属性
虽然你无法完全避免new
,但是你可以通过隐藏Article
内部各个属性的复制来提高代码的可读性,如下所示:
public class Article {
public string Name { get; set; }
public string Colour { get; set; }
public Article Rename(string newName) {
return new Article {
Name = newName
// Copy the remaining attributes
, Colour = this.Colour
};
}
}
现在你的LINQ看起来像这样:
var res = list.SelectMany(art => art.Name.Split(',').Select(n => art.Rename(n.Trim())));
这并没有删除任何代码,只是简单地重新调整了一些代码。但是,将Article
的属性复制到Article
会降低您忘记复制新添加的属性的机会。