首页 > 代码库 > LinQ转换运算符ToDictionary

LinQ转换运算符ToDictionary

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ToDictionaryDemo{    class Program    {        public class Game        {            public string Opponent { get; set; }            public string Score { get; set; }        }        static void Main(string[] args)        {            var spartans = new List<Game>            {                new Game{Opponent="UAB",Score="55-18"},                new Game{Opponent="Bowling Green",Score="55-18"},                new Game{Opponent="Pittsburgh",Score="55-18"},                new Game{Opponent="Notre Dame",Score="55-18"}            };            //字典是一种键值对的集合,ToDictionary 将一个IEnumerable<T>对象(比如LINQ查询所返回的结果)            //转换为一个IDictionary<Key,Value>对象。            IDictionary<string, Game> stats = spartans.ToDictionary(key => key.Opponent);            Console.WriteLine("Spartans vs. {0} {1}", stats["Notre Dame"].Opponent, stats["Notre Dame"].Score);            Console.ReadLine();        }    }}