当前位置: 首页>>代码示例>>C#>>正文


C# Dictionary.ToDictionary方法代码示例

本文整理汇总了C#中Dictionary.ToDictionary方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.ToDictionary方法的具体用法?C# Dictionary.ToDictionary怎么用?C# Dictionary.ToDictionary使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Dictionary的用法示例。


在下文中一共展示了Dictionary.ToDictionary方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParseInput

    static void ParseInput()
    {
        n = int.Parse(Console.ReadLine());

        stationsInfo = Regex.Matches(
                ("0 --> " + Console.ReadLine()).Replace(" --> ", "►"),
                "([^►]+)►([^►]+)"
            ).Cast<Match>()
            .Select(match =>
                new KeyValuePair<string, int>(
                    match.Groups[2].Value,
                    int.Parse(match.Groups[1].Value)
                )
            ).ToArray();

        int id = 0;
        stationsByName = stationsInfo.ToDictionary(
            info => info.Key,
            info => id++
        );

        stationsByIndex = stationsByName.ToDictionary(
            kvp => kvp.Value,
            kvp => kvp.Key
        );

        var separator = new string[] { " | " };

        camerasInfo = Enumerable.Range(0, int.Parse(Console.ReadLine()))
            .Select(_ => Console.ReadLine())
            .Select(line => line.Split(separator, StringSplitOptions.None))
            .Select(match =>
                new Tuple<DateTime, int, int, int, char>(
                    DateTime.ParseExact(match[0], DateFormat, CultureInfo.InvariantCulture),
                    stationsByName[match[1]],
                    int.Parse(match[2]),
                    int.Parse(match[3]),
                    match[4][0]
                )
            ).ToArray();

        trainCapacity = int.Parse(Console.ReadLine());

#if DEBUG
        //Console.WriteLine("# INPUT");

        //Console.WriteLine(string.Join(Environment.NewLine, stationsInfo));
        //Console.WriteLine();

        //Console.WriteLine(string.Join(Environment.NewLine, camerasInfo));
        //Console.WriteLine();

        //Console.WriteLine(trainCapacity);
        //Console.WriteLine();
#endif
    }
开发者ID:dgrigorov,项目名称:TelerikAcademy-1,代码行数:56,代码来源:Program.cs

示例2: SomeFunction

 public static void SomeFunction()
 {
     Dictionary<int, int> dict = new Dictionary<int, int>();
     dict.Add(4, 3);
     Console.WriteLine(dict[4]);
     Console.WriteLine(dict.ContainsKey(8));
     dict.Remove(4);
     foreach(int key in dict.Keys)
         Console.WriteLine(key);
     foreach(int val in dict.Values)
         Console.WriteLine(val);
     foreach(var kv in dict)
         Console.WriteLine(kv.Key + " " + kv.Value);
     var dict2 = dict.ToDictionary(o => o.Key, o => o.Value);
     var vals = dict.Values;
     
     HashSet<int> hash = new HashSet<int>();
     hash.Add(999);
     Console.WriteLine(hash.Contains(999));
     hash.Remove(999);
     Console.WriteLine(hash.Contains(999));
     foreach(int hashItem in hash)
         Console.WriteLine(hashItem);
     var z = hash.Select(o => 3).ToArray();
     var g = hash.GroupBy(o => o).Select(o => o.Count()).Min();
 }
开发者ID:mortezabarzkar,项目名称:SharpNative,代码行数:26,代码来源:DictionaryAndHashSet.cs

示例3: HistoryTickerStream

 public HistoryTickerStream(Dictionary<string, List<CandleDataBidAsk>> quotes)
 {
     this.quotes = quotes;
     if (quotes.Count == 0) return;
     currentIndex = quotes.ToDictionary(q => q.Key, q => 0);
     timeNow = quotes.Select(q => q.Value.Count == 0 ? DateTime.MaxValue : q.Value[0].timeClose).Min();
 }
开发者ID:johnmensen,项目名称:TradeSharp,代码行数:7,代码来源:HistoryTickerStream.cs

示例4: ConvertFrom

    public static Dictionary<string, List<SmallRNASequence>> ConvertFrom(List<ChromosomeCountSlimItem> items)
    {
      var result = new Dictionary<string, Dictionary<string, SmallRNASequence>>();
      foreach (var c in items)
      {
        foreach (var q in c.Queries)
        {
          Dictionary<string, SmallRNASequence> seqList;
          if (!result.TryGetValue(q.Sample, out seqList))
          {
            seqList = new Dictionary<string, SmallRNASequence>();
            result[q.Sample] = seqList;
          }

          if (!seqList.ContainsKey(q.Sequence))
          {
            seqList[q.Sequence] = new SmallRNASequence()
            {
              Sample = q.Sample,
              Sequence = q.Sequence,
              Count = q.QueryCount
            };
          }
        }
      }

      return result.ToDictionary(l => l.Key, l => l.Value.Values.ToList());
    }
开发者ID:shengqh,项目名称:CQS.Core,代码行数:28,代码来源:SmallRNASequenceUtils.cs

示例5: GenerateTextWithKey

        public async Task<Dictionary<string, string>> GenerateTextWithKey(CancellationToken cancellationToken)
        {
            var generatedTaskObjects = new Dictionary<string, Task<string>>();

            foreach (ExpressionWithSource expressionWithSource in _expressionsWithSources)
            {
                Expression expression = expressionWithSource.Expression;
                ExpressionSourceType source = expressionWithSource.Source;

                Task<string> generatedTextTask = GenerateTextAsync(expression, source, cancellationToken);

                string expressionNameResolvedDuplicates;
                if (generatedTaskObjects.Keys.Contains(expression.Name))
                {
                    int count = generatedTaskObjects.Keys.Count(x => x.StartsWith(expression.Name + " (")) + 1;
                    expressionNameResolvedDuplicates = expression.Name + " (" + count + ")";
                }
                else
                {
                    expressionNameResolvedDuplicates = expression.Name;
                }

                generatedTaskObjects.Add(expressionNameResolvedDuplicates, generatedTextTask);
            }

            await Task.WhenAll(generatedTaskObjects.Values);
            Dictionary<string, string> generatedObjects = generatedTaskObjects.ToDictionary(x => x.Key, y => y.Value.Result);

            return generatedObjects;
        }
开发者ID:JoshuaBelden,项目名称:ObjectExporter,代码行数:30,代码来源:ExportGenerator.cs

示例6: SimpleAppClient

        public SimpleAppClient(IRequester requester, Dictionary<Type, object> services)
            : base(requester)
        {
            foreach (var pair in services)
            {
                Type iface = pair.Key;

                if (iface == null)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                if (!iface.IsInterface)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                object instance = pair.Value;
                if (instance == null)
                {
                    throw new ApplicationException(); // todo2[ak]
                }

                if (!iface.IsAssignableFrom(instance.GetType()))
                {
                    throw new ApplicationException(); // todo2[ak]
                }
            }

            _proxies = services.ToDictionary(
                pair => pair.Key.FullName,
                pair => new Tuple<Type, object>(pair.Key, pair.Value));
        }
开发者ID:taucode,项目名称:taucode,代码行数:33,代码来源:SimpleAppClient.cs

示例7: BookPurchaseInfo

        public BookPurchaseInfo BookPurchaseInfo(string totalBudget, Dictionary<string, string> purchaseBook)
        {
            BookPurchaseInfo thisPurchaseInfo = new BookPurchaseInfo();

            if (String.IsNullOrWhiteSpace(totalBudget))
            {
                throw new NullReferenceException("Input field(s) is empty.");
            }
            else
            {
                try
                {
                    thisPurchaseInfo.budget = float.Parse(totalBudget);
                    thisPurchaseInfo.items = purchaseBook.ToDictionary(
                        x => int.Parse(x.Key),
                        x => int.Parse(x.Value)
                        );
                }
                catch (Exception Ex)
                {
                    throw new Exception(Ex.Message);
                }
            }

            return thisPurchaseInfo;
        }
开发者ID:ruchern,项目名称:INFS3204-Sem-2-2015,代码行数:26,代码来源:BookPurchaseService.svc.cs

示例8: IndependentMovements

        public void IndependentMovements()
        {
            /* take a grid and populate with organisms: |___|_A_|___|_B_|___|___|___|___|___|___|
             * make A choose rightmost stimulus & make B choose leftmost stimulus
             * no conflict, both organisms should move where they chose to go
             * result of test:                          |_A_|___|___|___|_B_|___|___|___|___|___| */

            var organismHabitats = new Dictionary<Organism, Habitat>
                                        {
                                            { this.organisms["A"], this.habitats[1, 0] },
                                            { this.organisms["B"], this.habitats[3, 0] }
                                        };

            var organismIntendedDestinations = new Dictionary<Organism, Habitat>
                                        {
                                            { this.organisms["A"], this.habitats[0, 0] },
                                            { this.organisms["B"], this.habitats[4, 0] }
                                        };

            var expectedOrganismDestinations = organismIntendedDestinations.ToDictionary(
                    intendedDestination => intendedDestination.Key,
                    intendedDestination => intendedDestination.Value);

            var updateSummary = this.CreateAndUpdateEcosystem(organismHabitats, organismIntendedDestinations);

            var expectedCoordinates = expectedOrganismDestinations.Values.Select(expectedDestination => this.habitatCoordinates[expectedDestination]).ToList();
            var actualCoordinates = updateSummary.PostUpdateOrganismLocations.Values.ToList();
            Assert.That(actualCoordinates, Is.EqualTo(expectedCoordinates));
        }
开发者ID:JoeyMuyo,项目名称:Colonies-Revisited,代码行数:29,代码来源:OrganismMovementTests.cs

示例9: InputState

		private InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs, InputState prev)
		{
			Mouse = ms;
			Keyboard = ks;
			TouchPanel = ts;
			GamePad = gs;

			if (Mouse.LeftButton == ButtonState.Pressed)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(Mouse.Position);
			}
			else if (TouchPanel.Count > 0)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint());
			}
			else
			{
				IsDown = false;
				PointerPosition = prev.PointerPosition;
			}

			IsJustDown = IsDown && !prev.IsDown;
			IsJustUp = !IsDown && prev.IsDown;

			lastKeyState = prev.currentKeyState;
			currentKeyState = lastKeyState.ToDictionary(p => p.Key, p => ks.IsKeyDown(p.Key));
		}
开发者ID:Mikescher,项目名称:GridDominance,代码行数:29,代码来源:InputState.cs

示例10: Font

 private Font(int height, Dictionary<char, byte[]> characters)
 {
     Height = height;
     this.characters = characters.ToDictionary(
         keyValue => keyValue.Key,
         keyValue => new Character(keyValue.Value, height));
 }
开发者ID:jmfb,项目名称:XComGenerations,代码行数:7,代码来源:Font.cs

示例11: Lexer

        /// <summary>
        ///     Initializes a new instance of the <see cref="Lexer" /> class.
        /// </summary>
        public Lexer()
        {
            // regex special characters (should be escaped if needed): .$^{[(|)*+?\
            var patterns = new Dictionary<TokenType, string>
            {
                {TokenType.AND, @"&&"},
                {TokenType.OR, @"\|\|"},
                {TokenType.LEFT_BRACKET, @"\("},
                {TokenType.RIGHT_BRACKET, @"\)"},
                {TokenType.GE, @">="},
                {TokenType.LE, @"<="},
                {TokenType.GT, @">"},
                {TokenType.LT, @"<"},
                {TokenType.EQ, @"=="},
                {TokenType.NEQ, @"!="},
                {TokenType.NOT, @"!"},
                {TokenType.NULL, @"null"},
                {TokenType.COMMA, @","},
                {TokenType.INC, @"\+{2}"}, // Despite the fact our language does not support ++ and -- prefix/postfix operations yet, these unary tokens are explicitly designated as illegal. We're detecting them to prevent unification which is done for consecutive plus or minus operators (e.g. + + - - +-+- => +).
                {TokenType.DEC, @"\-{2}"}, // Unification of such unary operators breaks compatibility - such mixed 1++ + 2 operations are illegal in both C# and JavaScript (since we control C# side there is not pain here, but JavaScript would fail since we're sending raw expressions to client-side).
                {TokenType.ADD, @"\+"},
                {TokenType.SUB, @"-"},
                {TokenType.MUL, @"\*"},
                {TokenType.DIV, @"/"},
                {TokenType.FLOAT, @"[0-9]*\.[0-9]+(?:[eE][\+-]?[0-9]+)?"}, // 1.0, 0.3e-2
                {TokenType.INT, @"[0-9]+"},
                {TokenType.BOOL, @"(?:true|false)"},
                {TokenType.STRING, @"(['])(?:\\\1|.)*?\1"}, // '1234', 'John\'s cat'
                {TokenType.FUNC, @"[a-zA-Z_]+(?:(?:(?:\[[0-9]+\])?\.[a-zA-Z_])?[a-zA-Z0-9_]*)*(?:\[[0-9]+\])?"} // field, field.field, arr[0], func(...)
            };

            RegexMap = patterns.ToDictionary(
                kvp => kvp.Key,
                kvp => new Regex(string.Format("^{0}", kvp.Value))); // in general, for compiled version of regular expressions their construction and initialization time is amortized out over many runs
        }
开发者ID:theyetiman,项目名称:ExpressiveAnnotations,代码行数:38,代码来源:Lexer.cs

示例12: IdentifyCustomer

        public async Task<bool> IdentifyCustomer(string customerId, string email, DateTime? dateCreatedUtc = null, Dictionary<string, string> extraData = null)
        {
            if (string.IsNullOrWhiteSpace(customerId))
                throw new ArgumentNullException("customerId may not be null or empty");

            if (string.IsNullOrWhiteSpace(email))
                throw new ArgumentNullException("email may not be null or empty");


            var request = new HttpRequestMessage(HttpMethod.Put, new Uri(ApiUrl + customerId));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", SiteId, ApiKey))));

            var dict = extraData == null ? new Dictionary<string, string>() : extraData.ToDictionary(d => d.Key, d => d.Value);

            if (dict.ContainsKey("email"))
            {
                throw new ArgumentOutOfRangeException("extraData may not contain a key called 'email'");
            }

            dict.Add("email", email);

            dict.Add("created_at",
                dateCreatedUtc != null
                    ? DateTimeToUnixTimestamp(dateCreatedUtc.Value).ToString("####")
                    : DateTimeToUnixTimestamp(DateTime.UtcNow).ToString("####"));

            request.Content = new FormUrlEncodedContent(dict);

            var response = await Client.SendAsync(request).ConfigureAwait(false);
            return ProcessResponseAsync(response);
        }
开发者ID:Med-Hx,项目名称:med-costumer-io,代码行数:31,代码来源:CustomerIoClient.cs

示例13: GroupGamesByGameInfo

        public Dictionary<SportType, Dictionary<GameInfo, List<Game>>> GroupGamesByGameInfo(
           Dictionary<SportType, List<Game>> games)
        {
            return games.ToDictionary(
               gamesOfSport => gamesOfSport.Key,
                gamesOfSport =>
                    {
                        var resultDict = new Dictionary<GameInfo, List<Game>>();
                        for (var i = 0; i < gamesOfSport.Value.Count; i++)
                        {
                            if (resultDict.Keys.All(info => info != gamesOfSport.Value[i].Info))
                            {
                                var tempList = new List<Game> { gamesOfSport.Value[i] };
                                for (var j = i + 1; j < gamesOfSport.Value.Count; j++)
                                {
                                    if (gamesOfSport.Value[i].BetsName != gamesOfSport.Value[j].BetsName
                                        & gamesOfSport.Value[i].Info == gamesOfSport.Value[j].Info)
                                    {
                                        tempList.Add(gamesOfSport.Value[j]);
                                    }
                                }

                                resultDict.Add(gamesOfSport.Value[i].Info, tempList);
                            }
                        }

                        return resultDict.Where(x => x.Value.Count > 1).ToDictionary(t => t.Key, t => t.Value);
                    });
        }
开发者ID:ForkerTeam,项目名称:Forker,代码行数:29,代码来源:GameGrouper.cs

示例14: GetBatchSentimentAsync

        public async Task<IDictionary<string, Result>> GetBatchSentimentAsync(Dictionary<string, string> textBatch)
        {
            ValidateBatchRequest(textBatch);

            if (!textBatch.Any())
            {
                return new Dictionary<string, Result>();
            }

            string content;
            using (var response = await _requestor.PostAsync(Constants.SentimentBatchRequest, BuildInputString(textBatch)))
            {
                content = await response.Content.ReadAsStringAsync();
                if (!response.IsSuccessStatusCode)
                {
                    return textBatch.ToDictionary(r => r.Key, r => AzureMachineLearningResult.Build(_errorMessageGenerator.GenerateError(response.StatusCode, content)));
                }
            }

            var result = JsonConvert.DeserializeObject<SentimentBatchResult>(content);
            var parsedResults = result.SentimentBatch.ToDictionary(sr => sr.Id, sr => AzureMachineLearningResult.Build(sr.Score, ScoreToSentiment(sr.Score)));

            foreach (var error in result.Errors)
            {
                parsedResults.Add(error.Id, AzureMachineLearningResult.Build(error.Message));
            }

            return parsedResults;
        }
开发者ID:bfdill,项目名称:SentimentAnalysis,代码行数:29,代码来源:SentimentAnalysisService.cs

示例15: Prepare

        internal override void Prepare()
        {
            Contract.Requires(!String.IsNullOrWhiteSpace(Database));
            Contract.Requires(!String.IsNullOrWhiteSpace(Username));

            var parameters = new Dictionary<String, String> {
                { "database",           Database },
                { "user",               Username },
                { "client_encoding",    "UTF8"   },
            };

            if (ApplicationName != null)
            {
                parameters.Add("application_name", ApplicationName);
            }

            if (SearchPath != null)
            {
                parameters.Add("search_path", SearchPath);
            }

            // TODO: Is this really UTF8 or can be ASCII?
            _parameters = parameters.ToDictionary(kv => PGUtil.UTF8Encoding.GetBytes(kv.Key),
                                                  kv => PGUtil.UTF8Encoding.GetBytes(kv.Value));
            _length = 4 + // len
                      4 + // protocol version
                      _parameters.Select(kv => kv.Key.Length + kv.Value.Length + 2).Sum() +
                      1; // trailing zero byte
        }
开发者ID:jbcooley,项目名称:Npgsql2,代码行数:29,代码来源:StartupMessage.cs


注:本文中的Dictionary.ToDictionary方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。