I found an Unexplainable behaviour of LINQ in a tutorial code example from this site:
How to: Populate Object Collections from Multiple Sources (LINQ) (C#)
https:
How to: Join Content from
starting from 2 Files:
names.csv
-----------------------------------
Omelchenko,Svetlana,111
O'Donnell,Claire,112
Mortensen,Sven,113
Garcia,Cesar,114
Garcia,Debra,115
Fakhouri,Fadi,116
Feng,Hanying,117
Garcia,Hugo,118
Tucker,Lance,119
Adams,Terry,120
Zabokritski,Eugene,121
Tucker,Michael,122
scores.csv
-----------------------------------
111, 97, 92, 81, 60
112, 75, 84, 91, 39
113, 88, 94, 65, 91
114, 97, 89, 85, 82
115, 35, 72, 91, 70
116, 99, 86, 90, 94
117, 93, 92, 80, 87
118, 92, 90, 83, 78
119, 68, 79, 88, 92
120, 99, 82, 81, 79
121, 96, 85, 91, 60
122, 94, 92, 91, 91
Code:
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }
public List<int> ExamScores { get; set; }
}
public static void Main()
{
string filepathname = @"C:\LINQPad\";
string[] names = System.IO.File.ReadAllLines(filepathname + "names.csv");
string[] scores = System.IO.File.ReadAllLines(filepathname + "scores.csv");
IEnumerable<Student> queryNamesScores =
from nameLine in names
let splitName = nameLine.Split(',')
from scoreLine in scores
let splitScoreLine = scoreLine.Split(',')
where splitName[2] == splitScoreLine[0]
select new Student()
{
FirstName = splitName[0],
LastName = splitName[1],
ID = Convert.ToInt32(splitName[2]),
ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
select Convert.ToInt32(scoreAsText)).
ToList()
};
List<Student> students = queryNamesScores.ToList();
foreach (var student in students)
{
Console.WriteLine("The average score of {0} {1} is {2}.",
student.FirstName, student.LastName,
student.ExamScores.Average());
}
}
Expected Output:
The average score of Omelchenko Svetlana is 82.5.
The average score of O'Donnell Claire is 72.25.
The average score of Mortensen Sven is 84.5.
The average score of Garcia Cesar is 88.25.
The average score of Garcia Debra is 67.
The average score of Fakhouri Fadi is 92.25.
The average score of Feng Hanying is 88.
The average score of Garcia Hugo is 85.75.
The average score of Tucker Lance is 81.75.
The average score of Adams Terry is 85.25.
The average score of Zabokritski Eugene is 83.
The average score of Tucker Michael is 92.
*/
* Real Output:
… nothing ….
*/
Why does LINQ not match correctly
At this point of code:
where splitName[2] == splitScoreLine[0]
And therefore no output will be generated
Thanks for advice
Alberto
ALBAB
|