2009-11-30 43 views
0

我正在使用以下命令将逗号分隔的字符串转换为列表。linq中的问题与逗号分隔的字符串

string productId ="1,2"; 
string productName = "Product1,Product2"; 
string prodCat = "Cat1,Cat1"; 
string quantity = "10,10"; 
string retailPrice = "12,12"; 

var _productId = new List<String>(productId.Trim().Split(',')); 
var _productName = new List<String>(productName.Trim().Split(',')); 
var _prodCat = new List<String>(prodCat.Trim().Split(',')); 
var _quantity = new List<String>(quantity.Trim().Split(',')); 
var _retailPrice = new List<String>(retailPrice.Trim().Split(',')); 
var _products = (from pi in _productId 
       join pro in _productName on _productId.IndexOf(pi) equals _productName.IndexOf(pro) 
       join pn in _prodCat on _productId.IndexOf(pi) equals _prodCat.IndexOf(pn) 
       join rp in _retailPrice on _productId.IndexOf(pi) equals _retailPrice.IndexOf(rp) 
       join q in _quantity on _productId.IndexOf(pi) equals _quantity.IndexOf(q) 
       where pi.Length > 0 && pro.Length > 0 
       select pi); 

_products.Dump("Products"); 

上面的查询返回不同的结果:

Products 

IEnumerable<String> (8 items) 
1 
1 
1 
1 
1 
1 
1 
1 

但它应该是:

Products 

IEnumerable<String> (2 items) 
1 
2 

如果我在所有的字符串不同的值,我得到的实际效果。在上面的例子中,我有两个不同产品的类别,数量和价格。但是我得到了八个错误值的结果。

对此的任何线索,为什么会发生这种情况?

回答

1

你想要做这样的事吗?

var _products = Enumerable.Range(0, _productId.Count) 
          .Select(i => new 
           { 
            Id = _productId[i], 
            Name = _productName[i], 
            Cat = _prodCat[i], 
            Quantity = _quantity[i], 
            RetailPrice = _retailPrice[i] 
           }); 
+0

这个让我的工作更轻松。 – Prasad

1

看起来您正在阅读CSV文件。如果是这种情况,最好使用CsvReader或其他库。 CSV文件中只有小部分可以被忽略。

至于你的问题。为什么不建立正常的对象并使用正常的Linq?像这样:

class Product { 
    public string Id { get; set; } 
    public string Name { get; set; } 
    public string Category {get; set; } 
    public int Quantity { get; set; } 
    public decimal RetailPrice { get; set; } 
} 

IList<Product> products = new List<Product>(); 
for (int i=0; i < _productId.Length; i++) { 
    products[i] = new Product { 
     Id = _productId[i], 
     Name = i < _productName.Length ? _productName[i] : null, 
     Category = i < _prodCat.Length ? _prodCat[i] : null, 
     Quantity= i < _quantity.Length ? int.Parse(_quantity[i]) : 0 // etc 
    }; 
} 

// Then use normal Linq2Objects: 
_products = products 
    .Where(c => !string.IsNullOrEmpty(c.Category)) 
    .Where(n => !string.IsNullOrEmpty(n.Name)) 
    .Select(x => x.Id); 
_products.Dump("Products")