【发布时间】:2012-04-11 17:13:25
【问题描述】:
我有一些代码,我知道如果在 LINQ 中完成会更好,但我不知道 LINQ 代码会是什么样子。
我有一个 GoodsItems 集合,在每个这个 Item 中都有一个 Collection of Comments,我想过滤掉其中的一些 cmets 并变成单个字符串行。
代码如下:
//-- 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,对于每个商品,我得到所有 cmets,其中评论的类型等于定义的值。
然后,对于我得到的这个评论,我创建一个新对象并添加到 CommentsCollection。
最后一件事是我循环通过这个 cmetsColletion 并将它的所有数据创建到单个字符串行中。
使用 LINQ 必须有更好、更智能的方法。
谢谢...
【问题讨论】:
标签: linq