我知道一些代码,如果在LINQ中完成,可能会更好,但我不知道LINQ代码的样子。
我有一个GoodsItems的集合,在这个Item的每一个中都有一个Comments of 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();
First Foreach循环遍历所有goodsitems,对于每个商品,我得到所有评论,其中评论的类型等于定义的值。
然后我得到这个评论,我创建一个新的Object并添加到CommentsCollection。
最后一件事是我通过这个commentsColletion循环并将它的所有数据创建成一个字符串行。
使用LINQ必须有一个更好,更聪明的方法。
...谢谢
答案 0 :(得分: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
代替注释的内容是。)