考虑以下代码片段;
foreach (var row in VtlDxGrid.GetSelectedRowHandles())
{
string name = Convert.ToString(VtlDxGrid.GetCellValue(row, "ContactName"));
string hn = Convert.ToString(VtlDxGrid.GetCellValue(row, "HouseName"));
string street1 = Convert.ToString(VtlDxGrid.GetCellValue(row, "StreetLine1"));
string street2 = Convert.ToString(VtlDxGrid.GetCellValue(row, "StreetLine2"));
string pt = Convert.ToString(VtlDxGrid.GetCellValue(row, "PostalTown"));
string pc = Convert.ToString(VtlDxGrid.GetCellValue(row, "PostCode"));
string country = Convert.ToString(VtlDxGrid.GetCellValue(row, "Country"));
SelectedAddress = $"{name} {hn ?? ":"} : {street1} : {street2 ?? ":"} {pt} : {pc} : {country}";
}
HouseName、StreetLine2 和 Country 可以包含空值。我需要得到一个字符串,其中包含由冒号分隔的值(如果county 为null,则末尾没有冒号)。
就我碰巧知道 HouseName 和 StreetLine2 为空而言,上述工作在一定程度上有效。然而,在这种情况下 Country 也是空的,最后我得到了一个冒号。
我可以将函数放在插值字符串中还是应该从不同的角度来处理?
编辑
在当前的例子中,我用 ;
吉姆鱼店 : Harold Road : HASTINGS : TN45 6QR :
我需要考虑这样一个事实,即所有三个可能为 null 的字段可能都不是,并且任何可以想象的 null 变体或一个值最终都会得到一个字符串,该字符串包含所有具有以冒号分隔的值的字段.
我会采取不同的方法。我不会将这些单元格读入单独的变量,而是添加到列表中,然后像这样使用 string.Join
List<string> theList = new List<string>();
theList.Add("The name");
theList.Add(null);
theList.Add("stree1 line 1");
theList.Add(null);
theList.Add("postal town");
theList.Add("postal code");
theList.Add(null);
Console.WriteLine(string.Join(":", theList.Where(l => !string.IsNullOrEmpty(l))))
在你的情况下,它会变得像
List<string> addressInfoList = new List<string>();
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "ContactName")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "HouseName")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "StreetLine1")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "StreetLine2")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "PostalTown")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "PostCode")));
addressInfoList.Add(Convert.ToString(VtlDxGrid.GetCellValue(row, "Country")));
Console.WriteLine(string.Join(":", addressInfoList.Where(l => !string.IsNullOrEmpty(l))));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句