0

我有一些我知道如果在 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 必须有更好、更智能的方法来做到这一点。

谢谢...

4

1 回答 1

1

看起来你可以这样做:

var comments = from goodsItem in shipmentInstructionMessage.ShipmentInstruction.ShipmentDetails.GoodsItems
               from freeText in goodsItem.Comments.Where(c => string.Equals(c.Type, FREETEXT_TYPE_GOODSDESCRIPTION, StringComparison.InvariantCultureIgnoreCase))
               select FreeText.CreateFreeTextFromCDMFreeText(freeText).ToString();
string contents = string.Join("", comments);

它可能更具可读性,只是因为您丢失了大多数类型(尽管您也可以使用隐式类型的局部变量来实现这一点)。

(我还更改了对注释类型进行字符串比较的方式——我假设您正在尝试实现大小写不变的比较。您可能希望使用它StringComparison.CurrentCultureIgnoreCase,具体取决于注释的内容。)

于 2012-04-11T08:58:31.060 回答