开发者

linq query and nulls

开发者 https://www.devze.com 2023-03-08 20:04 出处:网络
I would like to query with linq some xml file. There are some required and some optional elements. Only required is name - everything else is optional.

I would like to query with linq some xml file. There are some required and some optional elements. Only required is name - everything else is optional. If there is some NULL for example cageCode = NULL - it doesnt select anything - I need to add to List of strings - "" - I tried it like below, but it doesnt work. When I have everything filled it works fine, when there is something NULL it doesnt save to list anyth开发者_运维技巧ing. Could you help me how to set "" to list where is null element? Thanks!

var queryManufacturer = from dataManufaturer in input.Identification.Manufacturers.Manufacturer
                                                select
                                                new
                                                { 
                                                    dataManufaturer.name,
                                                    dataManufaturer.cageCode,
                                                    dataManufaturer.FaxNumber,
                                                    dataManufaturer.URL.OriginalString
                                                };

                foreach (var a in queryManufacturer)
                {
                    data.Add(a.name);
                    if (a.cageCode == null) data.Add("");
                    else data.Add(a.cageCode);
                    if (a.FaxNumber == null) data.Add("");
                    else data.Add(a.FaxNumber);
                    if (a.OriginalString == null) data.Add("");
                    else data.Add(a.OriginalString);
                }

It throws me a null exception if is some of elements in xml file missing - I dont wanna get this exception - I would like just add empty string beside missing element


try this in your Linq to XML query:

select new
{ 
  name = dataManufaturer.name ?? "",
  cageCode = dataManufaturer.cageCode ?? "",
  FaxNumber  = dataManufaturer.FaxNumber  ?? "",
  OriginalString = dataManufaturer.URL!=null ?  dataManufaturer.URL.OriginalString : ""
};
0

精彩评论

暂无评论...
验证码 换一张
取 消