2017-06-21 45 views
0

我在內存中有一個數據表,我需要從中選擇一些記錄,遍歷記錄對字段進行更改,並將更改返回到數據表。我可以使用過濾器,視圖和SQL來做到這一點,但我試圖在Linq中做到這一點。關於DataTable和更新記錄的Linq查詢

 var results = (from rows in dtTheRows.AsEnumerable() 
        select new 
        { 
         rows.Job, 
        }).Distinct(); 


    foreach (var row in results) 
    { 
     firstRow = true; 
     thisOnHand = 0; 

     var here = from thisRow in dtTheRows.AsEnumerable() 
         orderby thisRow.PromisedDate 
         select new 
         { 
          thisRow.OnHandQuantity, 
          thisRow.Balance, 
          thisRow.RemainingQuantity 
         }; 

     foreach(var theRow in here) 
     { 
      // business logic here ... 
      theRow.OnHandQuantity = 5; 

     } // foreach ... 

第一個linq查詢和foreach獲得了要考慮的數據子集列表。我把它包括在這裏以防它是相關的。我的問題是在這條線:

heRow.OnHandQuantity = 5; 

我的錯誤是: 「錯誤19屬性或索引‘AnonymousType#1.OnHandQuantity’不能被分配到 - 它是隻讀」

我是什麼在這裏失蹤?我可以將此查詢更新回原始數據表?

+0

可能重複的[C#匿名類型不能分配給 - 它是隻讀](https://stackoverflow.com/questions/1550797/c-sharp-anonymous-types-cannot-be-assigned-to-它-IS-只讀) – Igor

回答

0
var here = from thisRow in dtTheRows.AsEnumerable() 
         orderby thisRow.PromisedDate 
         select new 
         { 
          thisRow.OnHandQuantity, 
          thisRow.Balance, 
          thisRow.RemainingQuantity 
         }; 

不是傳遞三個變量的選擇中,通過thisRow本身。這可能會解決語句上的錯誤 - theRow.OnHandQuantity = 5;

0

錯誤是自描述性的,您不能更新/修改匿名類型。您必須從您的查詢中返回要修改的原始實體。

select thisRow; 

代替

select new 
{ 
    thisRow.OnHandQuantity, 
    thisRow.Balance, 
    thisRow.RemainingQuantity 
};