2015-01-12 2 views
0

나는 매월 배치 된 서비스 호출 목록을 포함하는 데이터 테이블을 가지고 있습니다. 열 F4에는 기계의 일련 번호가 들어 있습니다. 이제는 각 일련 번호에 대한 서비스 호출 수를 찾고 새 열에 추가하십시오. 아래의 코드를 작성하고 모두 잘 작동하지만 알 수 없거나 아직 할당 된 일련 번호를 반영하기 위해 해시 기호 '#'이 데이터에 나타날 때 문제가 발생합니다. 이로 인해 "수행 할 수 없습니다 '='System.String 및 System.Int32 작업 '오류가 발생했습니다.F4 열은 텍스트/문자열이고 데이터 테이블을 복제하고 수동으로 열을 .DataType = typeof (" 문자열). 나는 모든 괜찮 용도 변경 테스트의 데이터에서 제거 것처럼 나는이 문제를주고 그 # 기호를 알고있는 사람이 되거 수 많은 감사를 계산에 대해 걱정하지 마십시오C# Datatable.select가 데이터에서 # 해시 문자로 실패 함

// datatable dt contains all my monthly call data 
dt.Columns.Add("Counter", typeof(System.Int32)); // add a count column to the datatable    

for (int i = 0; i < dt.Rows.Count; i++) //loop through the datatable 
{ 
string chkStr = dt.Rows[i]["F4"].ToString(); // get 1st serial num, then each other one in loop 
DataRow[] FoundRows = dt.Select("[F4] =" + chkStr); // OK now select all the table rows containing this serial, place in FoundRows    
Int32 count = FoundRows.Length; // get the length which is a count of the same serial num/service calls     
dt.Rows[i]["Counter"] = count; 
} 

답변

0

을.. Int32에서와 같은 값입니다. 누가 문자열인지 여부를 여전히 "사용할"수 있습니다. 문자열로 읽으면 "#"이 유효하고 숫자가 유효합니다. 다음은 간단한 해결책입니다. 얼마나 많은 사람들이 아직 할당되지 않았습니까?

public class GroupCounter { 
    private Dictionary<string, int> serialNumbers; 

    public GroupCounter() { 
     this.serialNumbers = new Dictionary<string, int>(); 
    } 

    public Dictionary<string, int> Count(DataTable table) { 
     foreach (DataRow row in table.Rows) { 
      int counter; 
      string serial = row.Field<string>("COLUMN"); 
      if(!this.serialNumbers.TryGetValue(serial, out counter)){ 
       this.serialNumbers.Add(serial, 1); 
      } 
      counter++; 
     } 
     return this.serialNumbers; 
    } 
} 

사전을 반환하므로 사전 [키] (일련 번호)를 사용하여 가져 와서 일련 번호를 계산할 수 있습니다.

0

많은 의견을 주셔서 감사합니다. 그러나 답변을 찾으려면 chkStr 주변에 작은 따옴표를 추가하고 코드에서 # 해시 문자를 올바르게 처리해야합니다. 시간을 내 주셔서 감사합니다.

DataRow[] FoundRows = dt.Select("[F4] ='" + chkStr + "'");