简体   繁体   中英

Concatenate values in List

I have DTO consists of List of DeliveryNote, List of Customer. Each Delivery Note contains List of Quotations so that each delivery note have multiple quotations. But only same customer. Customer reference is in Quotations only.

I need to select the query like delivery note date, number and Reference in Quotation List separated by comma (if multiple).

I write LINQ like below

 var source = from A in _deliveryNote.DeliveryNoteList
     select new
           {
             A.ID,
             A.Date,
             A.Number,
             Reference = String.Join(", ", from item in A.Quotations select item.Reference),
             CustomerName = (A.Quotations != null ? _deliveryNote.CustomerList.Find(x => x.ID == A.Quotations.First().CustomerID).Name : string.Empty) 
                     };

This is working nice. But i need some tips like my unhandled case like if no quotations are available how it is handled and also when single wuotation is applicable how to avoid comma.

Also i got some other type of query like below.

var source = from A in _deliveryNote.DeliveryNoteList from B in A.Quotations
    select new
            {
               A.ID,
               A.Date,
               A.Number,
             //Reference = String.Join(", ", from item in A.Quotations select item.Reference),
             //CustomerName = (A.Quotations != null ? _deliveryNote.CustomerList.Find(x => x.ID == A.Quotations.First().CustomerID).Name : string.Empty) //_deliveryNote.CustomerList.Find(x => x.ID == C.CustomerID).Name : String.Empty)
               };

But here i don't know how i concatenate references and retrieve customer name

Please guide me which is better way and also what is the difference between both approach

Your concerns as stated in " But i need some tips like my unhandled case like if no quotations are available how it is handled and also when single wuotation is applicable how to avoid comma ", are already handled very well by String.Join method. You can prove it by doing a quick test as follow :

var data = new List<string>();
var str = String.Join(", ", data);
//you'll get empty string here
Console.WriteLine(str);

data.Add("test 1");
str = String.Join(", ", data);
//you'll get "test 1" here, no unnecessary comma appended
Console.WriteLine(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM