⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 frmcsvfile.cs

📁 移动设备的 LINQ 编程介绍 .NET Compact Framework 版 LINQ 的特性
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace Demo1___LinqToObjects
{
	public partial class FrmCsvFile : Form
	{
		string appPath;

		public FrmCsvFile()
		{
			InitializeComponent();

			appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
		}

		private void mniQueryScore_Click(object sender, EventArgs e)
		{
			textBox1.Text = "";

			string[] lines = Utility.ReadAllLines(appPath + @"\scores.csv");

			// Specifies the column to compute
			int exam = 3;

			// Spreadsheet format:
			// Student ID    Exam#1  Exam#2  Exam#3  Exam#4
			// 111,          97,     92,     81,     60
			// one is added to skip over the first column
			// which holds the student ID.
			SingleColumn(lines, exam + 1);

			textBox1.AppendLine();

			MultiColumns(lines);
		}

		private void SingleColumn(IEnumerable<string> strs, int examNum)
		{
			textBox1.AppendLine("Single Column Query:");

			// examNum specifies the column to run the 
			// calculations on. This could also be
			// passed in dynamically at runtime.             

			// columnQuery is a IEnumerable<int>
			// This query performs two steps:
			// 1) split the string into a string[]
			// 2) convert the specified element to
			//    int and select it.
			var columnQuery =
				from line in strs
				let x = line.Split(',')
				select Convert.ToInt32(x[examNum]);

			// Execute and cache the results for performance.
			// Only needed with very large files.
			var results = columnQuery.ToList();

			// Perform aggregate calculations 
			// on the column specified by examNum.
			double average = results.Average();
			int max = results.Max();
			int min = results.Min();

			textBox1.AppendLine(string.Format("Exam #{0}: Average:{1:##.##} High Score:{2} Low Score:{3}",
					 examNum, average, max, min));
		}

		private void MultiColumns(IEnumerable<string> strs)
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine("Multi Column Query:");

			// Create the columnQuery. Explicit typing is used
			// to make clear that the columnQuery will produce 
			// nested sequences. You can also just use 'var'.
			// The columnQuery performs these steps:
			// 1) convert the string to a string[]
			// 2) skip over the "Student ID" column and take the rest
			// 3) convert each string to an int and select that 
			//    entire sequence as one row in the results.
			IEnumerable<IEnumerable<int>> query =
				from line in strs
				let x = line.Split(',')
				let y = x.Skip(1)
				select (from str in y
						select Convert.ToInt32(str));

			// Execute and cache the results for performance.
			// ToArray could also be used here.
			var results = query.ToList();

			// Find out how many columns we have.
			int columnCount = results[0].Count();

			// Perform aggregate calculations on each column.            
			// One loop for each score column in scores.
			// We can use a for loop because we have already
			// executed the columnQuery in the call to ToList.
			for (int column = 0; column < columnCount; column++)
			{
				var res2 = from row in results
						   select row.ElementAt(column);
				double average = res2.Average();
				int max = res2.Max();
				int min = res2.Min();

				// 1 is added to column because Exam numbers
				// begin with 1
				sb.AppendFormat("Exam #{0} Average: {1:##.##} High Score: {2} Low Score: {3}",
							  column + 1, average, max, min).AppendLine();
			}
			textBox1.AppendLine(sb.ToString());
		}

		private void mniJoinContent_Click(object sender, EventArgs e)
		{
			// Join content from dissimilar files that contain
			// related information. names.csv contains the student name
			// plus an ID number. scores. csv contains the ID and a 
			// set of four test scores. The following query joins
			// the scores to the student names by using ID as a
			// matching key.

			string[] names = Utility.ReadAllLines(appPath + @"\names.csv");
			string[] scores = Utility.ReadAllLines(appPath + @"\scores.csv");


			// Name:    Last[0],       First[1],    StudentID[2]
			//          Omelchenko,    Svetlana,  111
			// Score:   StudentID[0],  Exam1[1]   Exam2[2],  Exam3[3],  Exam4[4]
			//             111,              97,            92,           81,           60

			// This query joins two dissimilar spreadsheets based on common ID value.
			// Multiple from clauses are used instead of a join clause
			// in order to store results of id.Split.
			IEnumerable<string> scoreQuery1 =
				from name in names
				let nameFields = name.Split(',')
				from id in scores
				let scoreFields = id.Split(',')
				where nameFields[2] == scoreFields[0]
				select nameFields[0] + "," + scoreFields[1] + "," + scoreFields[2]
					   + "," + scoreFields[3] + "," + scoreFields[4];

			// Pass a query variable to a method and
			// execute it in the method. The query itself
			// is unchanged.
			OutputQueryResults(scoreQuery1, "Merge two spreadsheets:");
		}

		private void OutputQueryResults(IEnumerable<string> query, string message)
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine(message);
			foreach (string item in query)
			{
				sb.AppendLine(item);
			}
			sb.AppendLine();
			sb.AppendFormat("{0} total names in list", query.Count());

			textBox1.Text = sb.ToString();
		}

	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -