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


C# Dictionary.Take方法代码示例

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


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

示例1: SelectBestRecettes

        public static List<Recette> SelectBestRecettes(List<Recette> recettes, List<Product> products, int limit = 3)
        {
            List<Tuple<int, List<string>>> lesMotsDesProduits = products.Select(o => new Tuple<int, List<string>>(o.ID, o.Libelle.Split(' ').ToList())).ToList();
            List<Tuple<int, List<List<string>>>> lesMotsDesRecettes = recettes.Select(o => new Tuple<int, List<List<string>>>(o.ID, o.Ingrédients.Select(i => i.Split(' ').ToList()).ToList())).ToList();

            lesMotsDesProduits.ForEach(o => o.Item2.RemoveAll(i => uselessWords.Contains(i)));
            lesMotsDesRecettes.ForEach(o => o.Item2.ForEach(l => l.RemoveAll(s => uselessWords.Contains(s))));

            Dictionary<int, int> classementRecette = new Dictionary<int, int>();

            foreach (Tuple<int, List<List<string>>> recette in lesMotsDesRecettes)
            {
                foreach (List<string> ingredient in recette.Item2)
                {
                    if (!classementRecette.ContainsKey(recette.Item1))
                    {
                        classementRecette[recette.Item1] = 0;
                    }
                    classementRecette[recette.Item1] += lesMotsDesProduits.Sum(o => o.Item2.Where(i => ingredient.Contains(i)).Count());
                }
            }
            classementRecette = classementRecette.OrderBy(o => o.Value).ToDictionary(o => o.Key, i => i.Value);

            return classementRecette.Values.All(o => o == 0) ? null : classementRecette.Take(limit).Select(r => recettes.Where(o => o.ID == r.Key && r.Value > 0).First()).ToList();
        }
开发者ID:pr0z,项目名称:Kuhlschrank,代码行数:25,代码来源:RecetteSelector.cs

示例2: TenMostFrequentChar

        private Dictionary<char, int> TenMostFrequentChar(string value)
        {
            var charDictionary = new Dictionary<char, int>();

            foreach (var x in value)
            {
                if (charDictionary.ContainsKey(x))
                {
                    charDictionary[x] = charDictionary[x] + 1;
                }
                else
                {
                    charDictionary.Add(x, 1);
                }
            }

            //This will order the Dictionary by the values
            charDictionary = charDictionary.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
            if (charDictionary.Count < 10)
            {
                return charDictionary;
            }
            else
            {
                return charDictionary.Take(10).ToDictionary(x => x.Key, x => x.Value);
            }
        }
开发者ID:Akilgour,项目名称:TextFileReader,代码行数:27,代码来源:TextAnalytics.cs

示例3: CreateCloud

 public Bitmap CreateCloud(Config config, Dictionary<string, int> words)
 {
     var bitmap = new Bitmap(config.ConfigModel.Width, config.ConfigModel.Height);
     using (var graphics = Graphics.FromImage(bitmap))
     {
         float height = 0;
         graphics.Clear(Color.FromName(config.ConfigModel.Background));
         var sum = words.Take(config.ConfigModel.Count).Sum(x => x.Value);
         foreach (var word in words.Take(config.ConfigModel.Count))
         {
             var wordHeight = (bitmap.Height/sum)*word.Value;
             DrawWord(word, graphics, wordHeight, height, config);
             height += wordHeight;
         }
     }
     return bitmap;
 }
开发者ID:Vedmax,项目名称:03-design-hw,代码行数:17,代码来源:SimpleDrawer.cs

示例4: SplitByRack

 private void SplitByRack(Dictionary<int, int> smpPlasmaSlices)
 {
     int totalSliceCnt = smpPlasmaSlices.Count;
     while (smpPlasmaSlices.Any())
     {
         int remaining = smpPlasmaSlices.Count;
         int splitted = totalSliceCnt - remaining;
         var tmpPlasmaSlices = smpPlasmaSlices.Take(Math.Min(remaining, 16)).ToDictionary(x => x.Key, x => x.Value);
         allRackSmpPlasmaSlices.Add(tmpPlasmaSlices);
         var tmpPackageInfos = CreatePackInfo(tmpPlasmaSlices);
         allPackageExpectedInfos.Add(new Dictionary<Point, string>(tmpPackageInfos));
         allPackageScannedInfos.Add(new Dictionary<Point, string>());
         smpPlasmaSlices = smpPlasmaSlices.Except(tmpPlasmaSlices).ToDictionary(x => x.Key, x => x.Value);
     }
     ChangeRackIndex(0);
 }
开发者ID:zhoukongjava,项目名称:Biobanking,代码行数:16,代码来源:Barcodes.cs

示例5: LoadSongs

        private string LoadSongs(string path, int category)
        {
            // read the index file from disk
            StreamReader sr = new StreamReader(path);
            string lyrics = sr.ReadToEnd();

            // parse the index file for songs and rank
            Dictionary<int, double> songs = new Dictionary<int, double>();
            foreach (string line in lyrics.Split('\n'))
            {
                try
                {
                    songs.Add(Convert.ToInt32(line.Split(' ')[0]), Convert.ToDouble(line.Split(' ')[1]));
                }
                catch (Exception ex)
                {
                    continue;
                }
            }

            // initialize web client
            WebClient client = new WebClient();

            // build the results output
            string output = "";
            foreach (KeyValuePair<int, double> song in songs.Take(5))
            {
                // download song information and album art from MusixMatch
                string response = client.DownloadString("http://api.musixmatch.com/ws/1.1/track.get?track_id=" + song.Key + "&apikey=" + apiKey);

                var track = Json.Decode(response).message.body.track;

                string albumCover = track.album_coverart_350x350 == "" ? track.album_coverart_100x100 : track.album_coverart_350x350;

                // append the raw HTML content
                output += "<div class='span2'><a href='view.aspx?id=" + track.track_id + "&category=" + category + "'><img class='img-polaroid' width='150' height='150' style='width: 150px; height: 150px;' src='" + albumCover + "'></a><h4><a href='view.aspx?id=" + track.track_id + "&category=" + category + "'>" + track.track_name + "</a></h4><p>by " + track.artist_name + "</p></div>\n";
            }

            // return the rendered results
            return output;
        }
开发者ID:purdue-cs-groups,项目名称:cs490-WIR-project01,代码行数:41,代码来源:Default.aspx.cs

示例6: Page_Load


//.........这里部分代码省略.........
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List<int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>();

                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                        into g
                            let count = g.Count()
                            orderby count descending
                            select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>();

                    foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }

                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }

                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);

                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible = true;
                    NoDISCResults.Visible = false;

                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }
开发者ID:NewPointe,项目名称:Rockit,代码行数:67,代码来源:ShapeResults.ascx.cs

示例7: PrintRequests

 private void PrintRequests(string type, Dictionary<string, int> sortedDict, int sum)
 {
     m_log.InfoFormat("[INFO]:");
     m_log.InfoFormat("[INFO]: {0,25}", type);
     foreach (KeyValuePair<string, int> kvp in sortedDict.Take(12))
         m_log.InfoFormat("[INFO]: {0,25} {1,-6}", kvp.Key, kvp.Value);
     m_log.InfoFormat("[INFO]: {0,25}", "...");
     m_log.InfoFormat("[INFO]: {0,25} {1,-6}", "Total", sum);
 }
开发者ID:hack13,项目名称:opensimulator,代码行数:9,代码来源:LindenUDPInfoModule.cs

示例8: SumSimilarity

        /// <summary>
        /// Vrátí součet rozdílů očekávaných a nalezených procentuálních výskytů znaků
        /// </summary>
        /// <param name="text"></param>
        /// <param name="occurrence"></param>
        /// <returns></returns>
        private static double SumSimilarity(string text, Dictionary<string, double> occurrence)
        {
            Dictionary<string, double> standardLettersOccurrence =
                occurrence.Take(6).ToDictionary(x => x.Key, x => x.Value);

            Dictionary<string, double> inTextLettersOcc = TextAnalysis.GetOccurrence(text, occurrence.Keys.Take(1).ToArray()[0].Length);

            double sum = 0;

            foreach (KeyValuePair<string, double> occ in standardLettersOccurrence)
            {
                if (inTextLettersOcc.ContainsKey(occ.Key))
                {
                    sum += Math.Abs(occ.Value - inTextLettersOcc[occ.Key]);
                }
                else
                {
                    sum += 10;
                }
            }

            return sum;
        }
开发者ID:havrlant,项目名称:cryptanalysis,代码行数:29,代码来源:Analyse.cs

示例9: GetFeeds

        public static List<FeedResultItem> GetFeeds(FeedApiFilter filter)
        {
            var filterOffset = filter.Offset;
            var filterLimit = filter.Max > 0 && filter.Max < 1000 ? filter.Max : 1000;

            var feeds = new Dictionary<string, List<FeedResultItem>>();

            var tryCount = 0;
            List<FeedResultItem> feedsIteration;
            do
            {
                feedsIteration = GetFeedsInternal(filter);
                foreach (var feed in feedsIteration)
                {
                    if (feeds.ContainsKey(feed.GroupId))
                    {
                        feeds[feed.GroupId].Add(feed);
                    }
                    else
                    {
                        feeds[feed.GroupId] = new List<FeedResultItem> { feed };
                    }
                }
                filter.Offset += feedsIteration.Count;
            } while (feeds.Count < filterLimit
                     && feedsIteration.Count == filterLimit
                     && tryCount++ < 5);

            filter.Offset = filterOffset;
            return feeds.Take(filterLimit).SelectMany(group => group.Value).ToList();
        }
开发者ID:vipwan,项目名称:CommunityServer,代码行数:31,代码来源:FeedAggregateDataProvider.cs

示例10: SearchActionMethod

        //serach bar action for ajax send
        public ActionResult SearchActionMethod(string word)
        {
            Dictionary<string[], int> words = new Dictionary<string[], int>();
            foreach (var item in client.GetProducts())
            {
                if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty)
                {
                    words.Add(new string[] { "pro", item.Name }, item.Id);

                }
            }
            foreach (var item in client.GetShipping_Companys())
            {
                if (item.Company_Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty)
                {
                    words.Add(new string[] { "com", item.Company_Name }, item.Id);
                }
            }
            foreach (var item in client.SubCategories())
            {
                if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty)
                {
                    words.Add(new string[] { "sub", item.Name }, item.Id);
                }
            }
            //foreach (var item in client.GetProducts())
            //{
            //    if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty)
            //    {
            //        words.Add("",item.Name);
            //    }
            //}
            foreach (var item in client.GetCategories())
            {
                if (item.Name.ToUpper().Contains(word.ToUpper()) && word != String.Empty)
                {
                    words.Add(new string[] { "cat", item.Name }, item.Id);
                }

            }
            //client.GetCategories();

            return Json(words.Take(7), JsonRequestBehavior.AllowGet);
        }
开发者ID:ilanitif,项目名称:finally,代码行数:45,代码来源:HomeController.cs

示例11: Iterate

        public void Iterate()
        {
            Dictionary<Particle, Rank> ranks = new Dictionary<Particle, Rank>();

            // Determine how strongly each Particle is being pulled in the four cardinal directions
            for (int x = 0; x < Size; ++x) {
                for (int y = 0; y < Size; ++y) {
                    Particle p = _lattice[x, y];
                    if (p == null)
                        continue;

                    Rank r = getParticleRank(p);
                    ranks.Add(p, r);
                }
            }

            // Compute the energy of the system in this Iteration
            _energy = ranks.Sum(r => Math.Abs(r.Value.Pulls[r.Value.MaxDirection]));

            // Sort the particles by the max magnitude of all their pull directions
            ranks = ranks.OrderBy(r => r.Value.Pulls[r.Value.MaxDirection])
                         .ToDictionary(r => r.Key, r => r.Value);

            // Process the Particles of highest rank (and any in their way) until all have been processed
            do {
                KeyValuePair<Particle, Rank> pair = ranks.Take(1).Single();
                processRank(pair.Key, pair.Value, ref ranks);
            } while (ranks.Count > 0);
        }
开发者ID:Rabadash8820,项目名称:UniverseSimulator,代码行数:29,代码来源:Simulator.cs

示例12: UpsertDocuments

        public void UpsertDocuments(Dictionary<string, string> docsToUpsert)
        {
            while (docsToUpsert.Any()) {
                var upsertBatch = docsToUpsert.Take (32).ToList ();
                upsertBatch.ForEach (b => docsToUpsert.Remove (b.Key));
                var upsertCommand = new StringBuilder ();
                foreach (var kvp in upsertBatch) {
                    var segments = kvp.Key.Split ('_');
                    string environment = segments [0];
                    string type = segments [1];

                    upsertCommand.AppendFormat ("exec UpsertDocument @id='{0}', @index='{1}', @type='{2}',  @doc='{3}'", kvp.Key, environment, type, kvp.Value.Replace ("'", "''"));
                }

                string sqlText = upsertCommand.ToString ();
                using (var _loadConnection = new SqlConnection(Common.TargetConnectionString)) {
                    _loadConnection.Open ();
                    using (var upsertCmd = new SqlCommand(sqlText, _loadConnection)) {
                        try {
                            upsertCmd.ExecuteNonQuery ();
                        } catch (SqlException sex) {
                            Console.WriteLine ("SqlException: {0}", sex.Message);
                            foreach (var d in upsertBatch) { // requeue these docs for upsert
                                docsToUpsert.Add (d.Key, d.Value);
                            }
                        }
                    }
                }
            }
        }
开发者ID:NGPVAN,项目名称:dnorml,代码行数:30,代码来源:SqlServerDataAccess.cs

示例13: S_1

        public ulong S_1(Dictionary<ulong, int> guesses)
        {
            ulong start = 1;
            ulong stop = 10;
            while(stop<guesses.First().Key)
            {
                start *= 10;
                stop *= 10;
            }

            var poss = new List<ulong>();

            foreach (var g in guesses.Take(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                for (ulong i = start; i < guess; i++)
                {
                    ulong diff = guess - i;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);

                }
                for (ulong i = guess + 1; i < stop; i++)
                {
                    ulong diff = i - guess;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count == correct)
                        poss.Add(i);
                }
            }

            foreach (var g in guesses.Skip(1))
            {
                ulong guess = g.Key;
                int correct = g.Value;

                foreach (var p in poss)
                {
                    ulong diff = p > guess ? p - guess : guess - p;
                    int count = 0;

                    while (diff > 0)
                    {
                        if (diff%10 == 0)
                        {
                            count++;
                            if (count > correct)
                            {
                                //continue to for loop
                                diff = 0;
                            }
                        }

                        diff /= 10;
                    }

                    if (count != correct)
                        poss.Remove(p);
                }
            }

            Debug.Assert(poss.Count==1);

            return poss.Single();
        }
开发者ID:charvey,项目名称:ProjectEuler,代码行数:100,代码来源:Problem185.cs

示例14: SearchDocumentSpace

        /// <summary>
        /// 
        /// </summary>
        /// <param name="req"></param>
        public SearchResponse SearchDocumentSpace(SearchRequest req)
        {
            SearchResponse resp = new SearchResponse();
            try
            {
                if (req == null || String.IsNullOrEmpty(req.DocumentSpace) || String.IsNullOrEmpty(req.SearchWords))
                    return resp;

                resp.DocumentSpace = req.DocumentSpace;

                Dictionary<int, Document> dmnts = new Dictionary<int, Document>();

                Action repack = () =>
                {
                    //Repacking dmnts into resp
                    if (req.IncludeDocuments)
                    {
                        foreach (var el in dmnts)
                        {
                            resp.Documents.Add(el.Value);
                        }
                    }
                    else
                    {
                        foreach (var el in dmnts)
                        {
                            resp.DocumentsInternalIds.Add(el.Key);
                        }
                    }
                };

                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();

                using (var tran = DBreezeEngine.GetTransaction())
                {
                    var mt = tran.SelectTable<int>(DocumentsStorageTablesPrefix + "m", 1, 0);
                    var docSpaceId = mt.Select<string, long>(req.DocumentSpace).Value;

                    if (docSpaceId == 0)
                        return resp;    //Not found document space

                    var Words = this.PrepareSearchKeyWords(req.SearchWords);

                    string docTable = DocumentsStorageTablesPrefix + "d" + docSpaceId.ToString();
                    var vt = tran.SelectTable<int>(docTable, 3, 0); //Version table Key
                    var dt = tran.SelectTable<int>(docTable, 1, 0); //Document table Key
                    dt.ValuesLazyLoadingIsOn = !req.IncludeDocuments;

                    DBreeze.DataTypes.Row<int, byte[]> docRow = null;
                    Document doc = null;
                    //byte[] btDoc = null;
                    int qOutput = 0;

                    //-----------------------------------------------------------------   ONE/MULTIPLE WORDS SEARCH then one word is supplied, using AND/OR LOGIC

                    #region "Multiple Words"

                    int j = -1;
                    List<byte[]> foundArrays = new List<byte[]>();
                    List<byte[]> oneWordFoundArrays = new List<byte[]>();
                    //WAH2 wh = null;
                    var tbOneWordWAH = tran.SelectTable<int>(DocumentsStorageTablesPrefix + "s" + docSpaceId.ToString(), 2, 0);
                    tbOneWordWAH.ValuesLazyLoadingIsOn = false;

                    resp.UniqueWordsInDataSpace = (int)tbOneWordWAH.Count();

                    bool anyWordFound = false;
                    int totalFoundWords = 0;

                    Dictionary<string, WordInDoc> words = new Dictionary<string, WordInDoc>();
                    int foundOrigin = 1;

                    Dictionary<string, WordInDoc> perWord = new Dictionary<string, WordInDoc>();
                    Dictionary<string, WordInDoc> firstHighOccuranceWord = new Dictionary<string, WordInDoc>();

                    //Currently we ignore these words and do nothing with them
                    List<string> highOccuranceWordParts = new List<string>();

                    foreach (var word in Words.Take(10)) //Maximum 10 words for search
                    {
                        anyWordFound = false;
                        totalFoundWords = 0;
                        perWord = new Dictionary<string, WordInDoc>();

                        foreach (var row1 in tbOneWordWAH.SelectForwardStartsWith<string, byte[]>(word))
                        {
                            anyWordFound = true;
                            totalFoundWords++;

                            if (Words.Count() == 1 && totalFoundWords > req.Quantity)
                            {
                                //In case if only one search word, then we don't need to make any comparation
                                break;
                            }
                            else if (totalFoundWords >= req.MaximalExcludingOccuranceOfTheSearchPattern)  //Found lots of words with such mask inside
//.........这里部分代码省略.........
开发者ID:enginekit,项目名称:DBreezeBased,代码行数:101,代码来源:Storage.cs

示例15: FormatLastInsertRecord

        private string FormatLastInsertRecord(Dictionary<string, string> row, Dictionary<string, string> fieldFormats, string prefixFormat, string fieldSeparator)
        {
            var sb = new StringBuilder();
            sb.AppendFormat(prefixFormat, "SELECT");

            foreach (var field in row.Take(row.Count - 1))
            {
                var fieldName = field.Key;
                sb.AppendFormat(fieldFormats[fieldName] + fieldSeparator, field.Value);
            }

            var lastField = row.Last();
            var lastFieldName = lastField.Key;
            sb.AppendFormat(fieldFormats[lastFieldName] + new string(' ', fieldSeparator.Length), lastField.Value);

            return sb.ToString();
        }
开发者ID:FishBasketGordo,项目名称:Creelio.Framework,代码行数:17,代码来源:SqlFormatHelper.cs


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