I have some code that I know could be nicer if it’s done in LINQ, but I don’t know how the LINQ code would look like.
I have a collection of GoodsItems, in each of this Item there is a Collection of Comments, and some of these comments I want to filter out and turn into a single string line.
Here is the code:
//-- 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 loops thru all goodsitems and for each goods item I get all comments where the Type of the comment is Equale to a defined value.
Then foreach of this comment that I get I create a new Object and add to a CommentsCollection.
And the last thing is that I loop thru this commentsColletion and create all it’s data into a single string line.
There must be a nicer and smart way to do this with LINQ.
Thanks…
It looks like you could do this:
It’s probably slightly more readable, if only because you’ve lost most of the types (although you could also have achieved this with implicitly typed local variables).
(I also changed how the string comparison on the comment type is done – I assume you were trying to achieve a case invariant comparison. You may want to use
StringComparison.CurrentCultureIgnoreCaseinstead, depending on what the content of the comments is.)