Skip to content

Commit c318d79

Browse files
authored
fix snippet error (#5929)
* fix snippet error * apply same changes to VB version * fix ms.date
1 parent 4eed018 commit c318d79

File tree

2 files changed

+270
-248
lines changed

2 files changed

+270
-248
lines changed
Lines changed: 141 additions & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -1,136 +1,147 @@
11
---
22
title: "How to: Populate Object Collections from Multiple Sources (LINQ) (C#)"
3-
ms.date: 07/20/2015
3+
ms.date: 06/12/2018
44
ms.assetid: 8ad7d480-b46c-4ccc-8c57-76f2d04ccc6d
55
---
66
# How to: Populate Object Collections from Multiple Sources (LINQ) (C#)
7-
This example shows how to merge data from different sources into a sequence of new types.
8-
7+
8+
This example shows how to merge data from different sources into a sequence of new types.
9+
910
> [!NOTE]
10-
> Do not try to join in-memory data or data in the file system with data that is still in a database. Such cross-domain joins can yield undefined results because of different ways in which join operations might be defined for database queries and other types of sources. Additionally, there is a risk that such an operation could cause an out-of-memory exception if the amount of data in the database is large enough. To join data from a database to in-memory data, first call `ToList` or `ToArray` on the database query, and then perform the join on the returned collection.
11-
12-
### To create the data file
13-
14-
- Copy the names.csv and scores.csv files into your project folder, as described in [How to: Join Content from Dissimilar Files (LINQ) (C#)](../../../../csharp/programming-guide/concepts/linq/how-to-join-content-from-dissimilar-files-linq.md).
15-
16-
## Example
17-
The following example shows how to use a named type `Student` to store merged data from two in-memory collections of strings that simulate spreadsheet data in .csv format. The first collection of strings represents the student names and IDs, and the second collection represents the student ID (in the first column) and four exam scores. The ID is used as the foreign key.
18-
19-
```csharp
20-
class Student
21-
{
22-
public string FirstName { get; set; }
23-
public string LastName { get; set; }
24-
public int ID { get; set; }
25-
public List<int> ExamScores { get; set; }
26-
}
27-
28-
class PopulateCollection
29-
{
30-
static void Main()
31-
{
32-
// These data files are defined in How to: Join Content from
33-
// Dissimilar Files (LINQ).
34-
35-
// Each line of names.csv consists of a last name, a first name, and an
36-
// ID number, separated by commas. For example, Omelchenko,Svetlana,111
37-
string[] names = System.IO.File.ReadAllLines(@"../../../names.csv");
38-
39-
// Each line of scores.csv consists of an ID number and four test
40-
// scores, separated by commas. For example, 111, 97, 92, 81, 60
41-
string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");
42-
43-
// Merge the data sources using a named type.
44-
// var could be used instead of an explicit type. Note the dynamic
45-
// creation of a list of ints for the ExamScores member. We skip
46-
// the first item in the split string because it is the student ID,
47-
// not an exam score.
48-
IEnumerable<Student> queryNamesScores =
49-
from nameLine in names
50-
let splitName = nameLine.Split(',')
51-
from scoreLine in scores
52-
let splitScoreLine = scoreLine.Split(',')
53-
where splitName[2] == splitScoreLine[0]
54-
select new Student()
55-
{
56-
FirstName = splitName[0],
57-
LastName = splitName[1],
58-
ID = Convert.ToInt32(splitName[2]),
59-
ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
60-
select Convert.ToInt32(scoreAsText)).
61-
ToList()
62-
};
63-
64-
// Optional. Store the newly created student objects in memory
65-
// for faster access in future queries. This could be useful with
66-
// very large data files.
67-
List<Student> students = queryNamesScores.ToList();
68-
69-
// Display each student's name and exam score average.
70-
foreach (var student in students)
71-
{
72-
Console.WriteLine("The average score of {0} {1} is {2}.",
73-
student.FirstName, student.LastName,
74-
student.ExamScores.Average());
75-
}
76-
77-
//Keep console window open in debug mode
78-
Console.WriteLine("Press any key to exit.");
79-
Console.ReadKey();
80-
}
81-
}
82-
/* Output:
83-
The average score of Omelchenko Svetlana is 82.5.
84-
The average score of O'Donnell Claire is 72.25.
85-
The average score of Mortensen Sven is 84.5.
86-
The average score of Garcia Cesar is 88.25.
87-
The average score of Garcia Debra is 67.
88-
The average score of Fakhouri Fadi is 92.25.
89-
The average score of Feng Hanying is 88.
90-
The average score of Garcia Hugo is 85.75.
91-
The average score of Tucker Lance is 81.75.
92-
The average score of Adams Terry is 85.25.
93-
The average score of Zabokritski Eugene is 83.
94-
The average score of Tucker Michael is 92.
95-
*/
96-
```
97-
98-
In the [select](../../../../csharp/language-reference/keywords/select-clause.md) clause, an object initializer is used to instantiate each new `Student` object by using the data from the two sources.
99-
100-
If you do not have to store the results of a query, anonymous types can be more convenient than named types. Named types are required if you pass the query results outside the method in which the query is executed. The following example performs the same task as the previous example, but uses anonymous types instead of named types:
101-
102-
```csharp
103-
// Merge the data sources by using an anonymous type.
104-
// Note the dynamic creation of a list of ints for the
105-
// ExamScores member. We skip 1 because the first string
106-
// in the array is the student ID, not an exam score.
107-
var queryNamesScores2 =
108-
from nameLine in names
109-
let splitName = nameLine.Split(',')
110-
from scoreLine in scores
111-
let splitScoreLine = scoreLine.Split(',')
112-
where splitName[2] == splitScoreLine[0]
113-
select new
114-
{
115-
First = splitName[0],
116-
Last = splitName[1],
117-
ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
118-
select Convert.ToInt32(scoreAsText))
119-
.ToList()
120-
};
121-
122-
// Display each student's name and exam score average.
123-
foreach (var student in queryNamesScores2)
124-
{
125-
Console.WriteLine("The average score of {0} {1} is {2}.",
126-
student.First, student.Last, student.ExamScores.Average());
127-
}
128-
```
129-
130-
## Compiling the Code
131-
Create a project that targets the .NET Framework version 3.5 or higher, with a reference to System.Core.dll and `using` directives for the System.Linq and System.IO namespaces.
132-
133-
## See Also
134-
[LINQ and Strings (C#)](../../../../csharp/programming-guide/concepts/linq/linq-and-strings.md)
135-
[Object and Collection Initializers](../../../../csharp/programming-guide/classes-and-structs/object-and-collection-initializers.md)
136-
[Anonymous Types](../../../../csharp/programming-guide/classes-and-structs/anonymous-types.md)
11+
> Don't try to join in-memory data or data in the file system with data that is still in a database. Such cross-domain joins can yield undefined results because of different ways in which join operations might be defined for database queries and other types of sources. Additionally, there is a risk that such an operation could cause an out-of-memory exception if the amount of data in the database is large enough. To join data from a database to in-memory data, first call `ToList` or `ToArray` on the database query, and then perform the join on the returned collection.
12+
13+
## To create the data file
14+
15+
Copy the names.csv and scores.csv files into your project folder, as described in [How to: Join Content from Dissimilar Files (LINQ) (C#)](../../../../csharp/programming-guide/concepts/linq/how-to-join-content-from-dissimilar-files-linq.md).
16+
17+
## Example
18+
19+
The following example shows how to use a named type `Student` to store merged data from two in-memory collections of strings that simulate spreadsheet data in .csv format. The first collection of strings represents the student names and IDs, and the second collection represents the student ID (in the first column) and four exam scores. The ID is used as the foreign key.
20+
21+
```csharp
22+
using System;
23+
using System.Collections.Generic;
24+
using System.Linq;
25+
26+
class Student
27+
{
28+
public string FirstName { get; set; }
29+
public string LastName { get; set; }
30+
public int ID { get; set; }
31+
public List<int> ExamScores { get; set; }
32+
}
33+
34+
class PopulateCollection
35+
{
36+
static void Main()
37+
{
38+
// These data files are defined in How to: Join Content from
39+
// Dissimilar Files (LINQ).
40+
41+
// Each line of names.csv consists of a last name, a first name, and an
42+
// ID number, separated by commas. For example, Omelchenko,Svetlana,111
43+
string[] names = System.IO.File.ReadAllLines(@"../../../names.csv");
44+
45+
// Each line of scores.csv consists of an ID number and four test
46+
// scores, separated by commas. For example, 111, 97, 92, 81, 60
47+
string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv");
48+
49+
// Merge the data sources using a named type.
50+
// var could be used instead of an explicit type. Note the dynamic
51+
// creation of a list of ints for the ExamScores member. The first item
52+
// is skipped in the split string because it is the student ID,
53+
// not an exam score.
54+
IEnumerable<Student> queryNamesScores =
55+
from nameLine in names
56+
let splitName = nameLine.Split(',')
57+
from scoreLine in scores
58+
let splitScoreLine = scoreLine.Split(',')
59+
where Convert.ToInt32(splitName[2]) == Convert.ToInt32(splitScoreLine[0])
60+
select new Student()
61+
{
62+
FirstName = splitName[0],
63+
LastName = splitName[1],
64+
ID = Convert.ToInt32(splitName[2]),
65+
ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
66+
select Convert.ToInt32(scoreAsText)).
67+
ToList()
68+
};
69+
70+
// Optional. Store the newly created student objects in memory
71+
// for faster access in future queries. This could be useful with
72+
// very large data files.
73+
List<Student> students = queryNamesScores.ToList();
74+
75+
// Display each student's name and exam score average.
76+
foreach (var student in students)
77+
{
78+
Console.WriteLine("The average score of {0} {1} is {2}.",
79+
student.FirstName, student.LastName,
80+
student.ExamScores.Average());
81+
}
82+
83+
//Keep console window open in debug mode
84+
Console.WriteLine("Press any key to exit.");
85+
Console.ReadKey();
86+
}
87+
}
88+
/* Output:
89+
The average score of Omelchenko Svetlana is 82.5.
90+
The average score of O'Donnell Claire is 72.25.
91+
The average score of Mortensen Sven is 84.5.
92+
The average score of Garcia Cesar is 88.25.
93+
The average score of Garcia Debra is 67.
94+
The average score of Fakhouri Fadi is 92.25.
95+
The average score of Feng Hanying is 88.
96+
The average score of Garcia Hugo is 85.75.
97+
The average score of Tucker Lance is 81.75.
98+
The average score of Adams Terry is 85.25.
99+
The average score of Zabokritski Eugene is 83.
100+
The average score of Tucker Michael is 92.
101+
*/
102+
```
103+
104+
In the [select](../../../../csharp/language-reference/keywords/select-clause.md) clause, an object initializer is used to instantiate each new `Student` object by using the data from the two sources.
105+
106+
If you don't have to store the results of a query, anonymous types can be more convenient than named types. Named types are required if you pass the query results outside the method in which the query is executed. The following example executes the same task as the previous example, but uses anonymous types instead of named types:
107+
108+
```csharp
109+
// Merge the data sources by using an anonymous type.
110+
// Note the dynamic creation of a list of ints for the
111+
// ExamScores member. We skip 1 because the first string
112+
// in the array is the student ID, not an exam score.
113+
var queryNamesScores2 =
114+
from nameLine in names
115+
let splitName = nameLine.Split(',')
116+
from scoreLine in scores
117+
let splitScoreLine = scoreLine.Split(',')
118+
where Convert.ToInt32(splitName[2]) == Convert.ToInt32(splitScoreLine[0])
119+
select new
120+
{
121+
First = splitName[0],
122+
Last = splitName[1],
123+
ExamScores = (from scoreAsText in splitScoreLine.Skip(1)
124+
select Convert.ToInt32(scoreAsText))
125+
.ToList()
126+
};
127+
128+
// Display each student's name and exam score average.
129+
foreach (var student in queryNamesScores2)
130+
{
131+
Console.WriteLine("The average score of {0} {1} is {2}.",
132+
student.First, student.Last, student.ExamScores.Average());
133+
}
134+
```
135+
136+
## Compiling the code
137+
138+
Create and compile a project that targets one of the following options:
139+
140+
- .NET Framework version 3.5 or higher with a reference to System.Core.dll.
141+
- .NET Core version 1.0 or higher.
142+
143+
## See also
144+
145+
[LINQ and Strings (C#)](../../../../csharp/programming-guide/concepts/linq/linq-and-strings.md)
146+
[Object and Collection Initializers](../../../../csharp/programming-guide/classes-and-structs/object-and-collection-initializers.md)
147+
[Anonymous Types](../../../../csharp/programming-guide/classes-and-structs/anonymous-types.md)

0 commit comments

Comments
 (0)