2013-05-13 5 views
0

배열의 각 요소의 출현을 계산하고 있지만 "값은 null이 될 수 없습니다"오류가 발생합니다. arr1이 마지막 5 개를 제외한 모든 null 값으로 채워지기 때문에 이것은 나에게 의미가 없습니다. null 인 요소배열의 카운팅 발생

여기 내 코드입니다. 나는 어딘가에 약간의 논리 오류가있을 수 있으므로 처음으로 사전을 사용하고 있습니다. 나는 텍스트 파일을 읽고있다.

string[] arr1 = new string[200]; 
StreamReader sr = new StreamReader("newWorkSheet.txt"); 
string Templine1 = ""; 
int counter = 0; 
while (Templine1 != null) 
{ 
    Templine1 = sr.ReadLine(); 
    arr1[counter] = Templine1; 
    counter += 1; 
} 
sr.Close(); 

// Dictionary, key is number from the list and the associated value is the number of times the key is found 
Dictionary<string, int> occurrences = new Dictionary<string, int>(); 
// Loop test data 
foreach (string value in arr1) 
{ 
    if (occurrences.ContainsKey(value)) // Check if we have found this key before 
    { 
     // Key exists. Add number of occurrences for this key by one 
     occurrences[value]++; 
    } 
    else 
    { 
     // This is a new key so add it. Number 1 indicates that this key has been found one time 
     occurrences.Add(value, 1); 
    } 
} 

// Dump result 
System.IO.StreamWriter sr2 = new System.IO.StreamWriter("OrganizedVersion.txt"); 
foreach (string key in occurrences.Keys) 
{ 
    sr2.WriteLine("Integer " + key.ToString() + " was found " + occurrences[key].ToString() + " times"); 
} 
sr2.Close(); 
Console.ReadLine(); 

편집 : 나는 여기에 선언문을 포함하여 모든 코드를 넣었습니다.

+0

'arr1'과'counter'의 선언과 초기화를 보여줍니다. –

답변

1

내 돈은 너비가 arr1입니다. 미리 크기를 알아야하지만 변경 될 수있는 파일의 줄을 채우고 있습니다. 좋은 점은 당신이 실제로 그것을 필요로하지 않는다는 것입니다.

foreach(string value in File.ReadLines("fileName")) 
{ 
} 

MSDN File.ReadLines

+0

mg! @ 오스틴 Salonen 당신의 솔루션이 작동했습니다! 어떤 종류의 마술 지팡이를 치셨습니까? – Harmond

+0

@Harmond : 그것은이 foreach는 (문자열 occurrences.Keys에서 키) { Console.WriteLine (key.ToString() + ","+ 발생 [키]를 작동하는 이유는 무엇 단지 경험 ... –

+0

입니다 .ToString()); } 하지만 sr2.WriteLine을 사용하여 출력을 파일에 쓰려고하면 파일의 마지막 줄만 텍스트 파일에 씁니다. – Harmond

4

그것은 정확히 질문입니다 만 Linq는 여기에 행의 수를 줄일 수있다 :이 함께 ... foreach (string value in arr1)

을 :

이 교체

var groups = arr1.GroupBy(item => item); 
foreach (var group in groups) 
{ 
    Console.WriteLine(string.Format("{0} occurences of {1}", group.Count(), group.Key); 
} 
+0

예 Linq가 답입니다. 어쩌면 ToDictionary()와 함께 변형을 추가 할 수 있습니다. –

+1

@HenkHolterman ToDook은 ToLookup이 작동 할 때 동일한 키를 가진 여러 항목이 있기 때문에 여기서는 작동하지 않습니다 –

+1

두 가지를 사용하여'.ToLookup (...)과 같은 수의 사전을 구할 수 있습니다. ToDictionary (x = > x.Key, x => x.Count())'. 'GroupBy'는'ToLookup' 대신에 작동 할 것입니다,이 인스턴스에 차이가 있다면 확실하지 않습니다. –

0

루프에 루프가 있는지 확인해야합니다. 당신의 가치 null

foreach (string value in arr1) 
{ 
    if (!string.IsNullOrEmpty(value)) 
    { 
     ........ 

이것은 당신이 파일에서 발생할 수있는 문제 처리됩니다.

1

아니 "arr1가 완전히없는 널 (null) 값으로 채워집니다". 배열에 넣은 마지막 항목은 null입니다. 당신이 방법 더 좋아

while (true) { 
    Templine1 = sr.ReadLine(); 
    if (Templine1 == null) break; 
    arr1[counter++] = Templine1; 
} 

또는 :

이제
while ((Templine1 = sr.ReadLine()) != null) { 
    arr1[counter++] = Templine1; 
} 

, 인덱스 counter까지 루프 대신 전체 배열을 통해 반복의 관계없이 배열에 넣어 전에 값을 확인

for (int i = 0; i < counter; i++) { 
    string value = arr1[i]; 
    ... 
} 
+0

마지막 항목이 null이라는 것이 맞습니다. – Harmond

+0

하지만 마지막 null을 제거한 후에도이 오류가 발생합니다 .. – Harmond

+0

@Harmond : 배열을 사용하는 루프를 변경 했습니까? – Guffa