问题描述
我是 linq 的新手,这会不断出现在空卷字段上.该文件是不可预测的,它会发生,所以我想在有异常的地方放一个 0.有什么快速简单的方法吗?
var qry = from line in File.ReadAllLines("C:\\temp\\T.txt") let myRecX = line.Split(',') select new myRec() { price = Convert.ToDecimal( myRecX[0].Replace("price = ", "")) , volume = Convert.ToInt32(myRecX[1].Replace("volume =", "")), dTime = Convert.ToDateTime( myRecX[2].Replace("timestamp =", "")) };
推荐答案
如果您想在传入数据为 null、空或完全由空白字符组成时使用默认值,您可以这样做:
volume = string.IsNullOrWhitesplace(myRecX[1]) ? defaultVolume // <<== You can use any constant here : Convert.ToInt32(myRecX[1].Replace("volume =", ""))
但是,这是实现您需要的"快速而肮脏"的方式,因为每个命名参数的位置仍然是硬编码的.一种更健壮的方法是编写一个小型解析器,它关注文件中指定的属性名称,而不是用空字符串替换它们.
问题描述
I am new to linq, and this keeps popping on a null volume field. The file is unpredictable, and it will happen so I would like to put a 0 in where there is an exception. any quick and easy way to do it?
var qry = from line in File.ReadAllLines("C:\\temp\\T.txt") let myRecX = line.Split(',') select new myRec() { price = Convert.ToDecimal( myRecX[0].Replace("price = ", "")) , volume = Convert.ToInt32(myRecX[1].Replace("volume =", "")), dTime = Convert.ToDateTime( myRecX[2].Replace("timestamp =", "")) };
推荐答案
If you would like to use a default when the incoming data is null, empty, or consists entirely of whitespace characters, you can do it like this:
volume = string.IsNullOrWhitesplace(myRecX[1]) ? defaultVolume // <<== You can use any constant here : Convert.ToInt32(myRecX[1].Replace("volume =", ""))
However, this is a "quick and dirty" way of achieving what you need, because the position of each named parameter remains hardcoded. A more robust way would be writing a mini-parser that pays attention to the names of attributes specified in the file, rather than replacing them with an empty string.