我有一些我知道如果在 LINQ 中完成可能会更好的代码,但我不知道 LINQ 代码会是什么样子。
我有一个 GoodsItems 集合,在每个 Item 中都有一个 Comments 集合,我想过滤掉其中的一些评论并变成单个字符串行。
这是代码:
//-- get all comments that is of type "GoodsDescription"
ICollection<FreeText> comments = new List<FreeText>();
foreach (DSV.Services.Shared.CDM.Shared.V2.GoodsItem goodsItem in shipmentInstructionMessage.ShipmentInstruction.ShipmentDetails.GoodsItems)
{
ICollection<DSV.Services.Shared.CDM.Shared.V2.FreeText> freeTexts = goodsItem.Comments.Where(c => c.Type.ToLower() == FREETEXT_TYPE_GOODSDESCRIPTION.ToLower()).ToList();
foreach (DSV.Services.Shared.CDM.Shared.V2.FreeText freeText in freeTexts)
comments.Add(FreeText.CreateFreeTextFromCDMFreeText(freeText));
}
//-- Turn this collection of comments into a single string line
StringBuilder sb = new StringBuilder();
foreach (FreeText comment in comments)
sb.Append(comment.ToString());
contents = sb.ToString();
第一个 Foreach 循环遍历所有 goodsitems,对于每个商品项目,我得到所有评论,其中评论的类型等于定义的值。
然后,对于我得到的每条评论,我都会创建一个新对象并添加到 CommentsCollection 中。
最后一件事是我循环通过这个 commentsColletion 并将它的所有数据创建到单个字符串行中。
使用 LINQ 必须有更好、更智能的方法来做到这一点。
谢谢...