public static List<ClrType> GetDelegateTypes(ClrDump clrDump)
        {
            CancellationTokenSource token = new CancellationTokenSource();
            clrDump.MessageBus.BeginTask("Analyzing delegate types...", token);
            List<ClrType> delegates = new List<ClrType>();
            var delegateType = clrDump.GetClrType(typeof(MulticastDelegate).FullName);

            foreach(var type in  clrDump.AllTypes)
            {
                clrDump.MessageBus.Status($"Analyzing delegate type: {type.Name}");
                if (token.IsCancellationRequested)
                {
                    break;
                }

                if ( type.BaseType != null && type.BaseType == delegateType )
                {
                    clrDump.MessageBus.Status($"Analyzing delegate type: counting instances for {type.Name}");
                    int nb = clrDump.CountInstances(type);
                    if (nb > 0)
                    {
                        delegates.Add(type);
                    }
                }
            }

            clrDump.MessageBus.EndTask("Delegate types analyzed.");
            return delegates.GroupBy(t => t.Name).Select(g => g.First()).ToList();
        }
        public void BasicCount_PossiblyRelated()
        {
            var people = new List<Person>
            {
                new Person{ Firstname="Jim", Lastname="Bob" },
                new Person{ Firstname="Joe", Lastname="Bob" },
                new Person{ Firstname="Joe", Lastname="John" },
            };

            Console.WriteLine("Group and count");

            var groupedAndCounted = people
                                    .GroupBy(person => person.Lastname)
                                    .Select(grouping => new { Lastname = grouping.Key, Count = grouping.Count() })
                                    .ToList();

            Console.WriteLine(string.Join(Environment.NewLine,
                                groupedAndCounted.Select(personStats => string.Format("Lastname={0}, Count={1}",
                                                                                        personStats.Lastname,
                                                                                        personStats.Count)).ToArray()));

            Console.WriteLine("Group and count. Only include items that occur more than once.");

            var possibleRelatives = people
                                    .GroupBy(person => person.Lastname)
                                    .Select(grouping => new { Lastname = grouping.Key, Count = grouping.Count() })
                                    .Where(personStats => personStats.Count > 1)
                                    .ToList();

            Console.WriteLine(string.Join(Environment.NewLine,
                                possibleRelatives.Select(personStats => string.Format("Lastname={0}, Count={1}",
                                                                                        personStats.Lastname,
                                                                                        personStats.Count)).ToArray()));
        }
Example #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Interview App");
            List<string> names = new List<String> { "dave", "Dave", "DAVE", "ian", "Ian", "IAN", "Ben" };
            List<Int32> numbers = new List<Int32> {12, 10, 9, 8, 18, 22, 20,20,12,10,9,8,18};
            List<Int32> duplicatenumbers = numbers.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
            List<Int32> uniquenumbers = numbers.Distinct().ToList();
            List<string> duplicatenames = names.GroupBy(name => name.ToLower()).Where(name => name.Count() > 1).Select(name => name.Key).ToList();
            List<string> uniquenames = names.GroupBy(name => name.ToLower()).Where(name => name.Count() == 1).Select(name => name.Key).ToList();

            foreach (var name in duplicatenames)
            {
                Console.WriteLine("Duplicate: " + name);
            }

            foreach (var name in uniquenames)
            {
                Console.WriteLine("Unique: " + name);
            }

            foreach (var number in duplicatenumbers)
            {
                Console.WriteLine("Duplicate: " + number.ToString());
            }

            foreach (var number in uniquenumbers)
            {
                Console.WriteLine("Unique: " + number.ToString());
            }

            Console.ReadLine();
        }
        static void Main()
        {
            var list = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3 };

            var size = (list.Count / 2) + 1;

            var number = list
                .GroupBy(g => g)
                .Where(s => s.Count() > size)
                .Select(x => x.Key);

            if (number.Any())
            {
                Console.WriteLine(string.Join(",", number));
            }
            else
            {
                Console.WriteLine("no result");
            }

            Console.WriteLine(new string('-', 20));
            Console.WriteLine("Additional info:");
            Console.WriteLine(new string('-', 20));
            Console.WriteLine("Size: N/2 + 1 = {0}", size);
            var occurances = list.GroupBy(o => o);
            foreach (var occurance in occurances)
            {
                Console.WriteLine("Number[{0}] -> {1} times", occurance.Key, occurance.Count());
            }
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Clear();
            _sqlRecordList = Common.LoadLog<LogEntity>(Common.RunExceptionLogPathKey);
            _sqlRecordList = _sqlRecordList.OrderByDescending(o => o.CreateAt.ToString("yy-MM-dd HH:mm")).ToList();

            foreach (var result in _sqlRecordList.GroupBy(o => o.CreateAt.ToString("yy-MM-dd"))) { if (result.Key != null) { coxDate.Items.Add(result.Key); } }
            foreach (var result in _sqlRecordList.GroupBy(o => o.MethodName)) { if (result.Key != null) { coxMethodName.Items.Add(result.Key); } }

            btnSelect.PerformClick();
        }
Example #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        list = Medlem.GetMedlemmer();

        rptDepartments.DataSource = list.GroupBy(x => x.Årgang).OrderBy(x => x.Key).Select(x => new { Afdeling = x.Key }).ToList();

        if( !IsPostBack )
            dd.Items.AddRange(list.GroupBy(x => x.Årgang).OrderBy(x => x.Key).Select(x => new ListItem { Text = x.Key }).ToArray());

        if( Request.QueryString["afdeling"] != null )
            memberList.DataSource = list.Where(x => x.Årgang.StartsWith(Afdeling));
        DataBind();
    }
        public void Update(RealTimeData s)
        {
            List<BuyOrder> buylist = new List<BuyOrder>();
                int i = 0;
                foreach (BuyOrder value in comp.Buyorder)
                {
                    if (i < 10)
                        buylist.Add(value);
                    i++;
                }
                realdata = s;
                dataGridView1.Rows.Clear();
                IEnumerable<IGrouping<float, BuyOrder>> collection = buylist.GroupBy(b => b.orderPrice).OrderBy(b => b.Key).Reverse();

                foreach (IGrouping<float, BuyOrder> orders in collection)
                {

                    int vol = 0;

                    //go through each buyorder
                    foreach (BuyOrder buyo in orders)
                    {
                        vol += buyo.orderSize;
                        //pocket full of mumbles
                        dataGridView1.Rows.Add(orders.Count(), vol, orders.Key);//orders.count() is how many times that order was made

                    }

                }

                IEnumerable<IGrouping<float, BuyOrder>> collection2 = buylist.GroupBy(b => b.orderPrice).OrderBy(b => b.Key).Reverse();

                dataGridView2.Rows.Clear();
                foreach (IGrouping<float, BuyOrder> orders2 in collection2)
                {

                    int vol = 0;

                    //go through each buyorder
                    foreach (BuyOrder buyo in orders2)
                    {
                        vol += buyo.orderSize;
                        //pocket full of mumbles
                        dataGridView2.Rows.Add(orders2.Count(),vol, orders2.Key);//orders.count() is how many times that order was made

                    }

                }
        }
        public static void Main()
        {
            List<Student> students = new List<Student>();
            Student ivan = new Student("Ivan", "Ivanov", "141000", "02325123", "[email protected]", 1);
            students.Add(ivan);
            Student gosho = new Student("Gosho", "Goshev", "141001", "052222222", "[email protected]", 1);
            students.Add(gosho);
            Student pesho = new Student("Pesho", "Mastikata", "141002", "052123634", "[email protected]", 2);
            students.Add(pesho);
            Student kiro = new Student("Kiro", "Leshnikov", "141003", "03225123", "[email protected]", 2);
            students.Add(kiro);
            Student maria = new Student("Maria", "Dimitrova", "141004", "056251231", "[email protected]", 3);
            students.Add(maria);
            Student vanq = new Student("Vanq", "Ivanova", "141005", "032412413", "[email protected]", 2);
            students.Add(vanq);

            var groups = students.GroupBy(student => student.GroupNumber);
            //foreach (var group in groups)
            //{
            //    Console.WriteLine("Group: " + group.Key);
            //    foreach (var name in group)
            //    {
            //        Console.WriteLine("\t{0} {1}", name.FirstName, name.LastName);
            //    }
            //}

            var orderedGroups = students.OrderByGroup();
            foreach (var orderedItems in orderedGroups)
            {
                Console.WriteLine("Group: " + orderedGroups);
                Console.WriteLine("\t{0} {1}", orderedItems.FirstName, orderedItems.LastName);
            }
        }
        public List<IPatient> RemoveExistingPatients(List<IPatient> patients)
        {
            foreach (var patientGroup in patients.GroupBy(p => p.GetCPF()).GroupBy(e => e.Key))
            {
                foreach (var patientValue in patientGroup)
                {
                    IPatient patientUnique = new Patient();

                    foreach (var patient in patientValue)
                    {
                        if (string.IsNullOrEmpty(patientUnique.Id))
                        {
                            patientUnique = patient;
                            patient.AddRecord(new Record() { Code = patient.Id, Hospital = patient.Hospital });
                            PatientsDb.Add(patient);
                        }
                        else
                        {
                            if (patientUnique.Records != null)
                            {
                                var record = patientUnique.Records.Find(r => r.Code == patient.Id);

                                if (record != null)
                                    continue;
                            }

                            patientUnique.AddRecord(new Record() { Code = patient.Id, Hospital = patient.Hospital });
                        }
                    }
                }
            }

            return PatientsDb;
        }
        static void Main(string[] args)
        {
            int[] arr = new int[5];
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine("Enter a number");
                arr[i] = int.Parse(Console.ReadLine());
            }
            List<int> red = new List<int>(arr);

            var group = red.GroupBy(i => i);

            foreach (var item in group)
            {
                List<int> red2 = new List<int>();
                Console.WriteLine("The number {0} occurs {1} times", item.Key, item.Count());
                if(item.Count()%2!=0)
                {
                                    
                        red2.Add(red[item.Count()]);
                }
                    foreach (var gs in red2)
                    {
                        Console.WriteLine(gs);
                    }

                }
            }
        /// <summary>
        /// Gets the presenter bindings for passed views using the passed hosts.
        /// </summary>
        /// <param name="hosts">A list of view hosts (master pages, pages, etc).</param>
        /// <param name="viewInstances">A list of view instances (user controls, pages, etc).</param>
        public IEnumerable<PresenterDiscoveryResult> GetBindings(IEnumerable<object> hosts, IEnumerable<IView> viewInstances)
        {
            var results = new List<PresenterDiscoveryResult>();

            var pendingViewInstances = viewInstances;
            foreach (var strategy in strategies)
            {
                if (!pendingViewInstances.Any())
                    break;

                var resultsThisRound = strategy.GetBindings(hosts, pendingViewInstances);

                results.AddRange(resultsThisRound);

                var viewsBoundThisRound = resultsThisRound
                    .Where(r => r.Bindings.Any())
                    .SelectMany(b => b.ViewInstances)
                    .Distinct();

                pendingViewInstances = pendingViewInstances
                    .Except(viewsBoundThisRound);
            }

            return results
                .GroupBy(r => r.ViewInstances, viewInstanceListComparer)
                .Select(r => BuildMergedResult(r.Key, r));
        }
 //Write a program to find the longest area of equal elements in array of strings.You first should read an integer n and n strings(each at a separate line), then find and print the longest sequence of equal elements(first its length, then its elements). If multiple sequences have the same maximal length, print the leftmost of them.
 static void Main()
 {
     Console.Write("n = ");
     int n = int.Parse(Console.ReadLine());
     List<string> strings = new List<string>();
     for (int i = 0; i < n; i++)
     {
         strings.Add(Console.ReadLine());
     }
     var result = strings.GroupBy(x => x).Select(x => new
     {
         Name = x.Key,
         Total = x.Count()
     });
     int biggestCount = 0;
     string longestArea = "";
     foreach (var s in result)
     {
         if (s.Total > biggestCount)
         {
             biggestCount = s.Total;
             longestArea = s.Name;
         }
     }
     Console.WriteLine(biggestCount);
     for (int i = 0; i < biggestCount; i++)
     {
         Console.WriteLine(longestArea);
     }
 }
Example #13
0
        public static void Test()
        {
            List<Experiment> list = new List<Experiment>();
            for (int i = 0; i < 100; i++)
            {
                var exp = new Experiment();
                exp.ExpNo = Guid.NewGuid().ToString();
                exp.LayerNo = i.ToString();
                if (i < 30)
                {
                    exp.AppVersion = "7.2.3";
                }
                else if (i < 60)
                {
                    exp.AppVersion = "7.2.4";
                }
                else
                {
                    exp.AppVersion = "7.3";
                }
                list.Add(exp);
            }

            Dictionary<string, List<Experiment>> result = new Dictionary<string, List<Experiment>>();
            var groups = list.GroupBy(g => g.AppVersion);
            foreach (var item in groups)
            {
                result[item.Key] = item.ToList();
            }


            Console.WriteLine("a");
        }
Example #14
0
        public NaiveBayes(List<Case> cases)
        {
            this.classProbabilities = new List<ClassGrouping>();
            this.attrProbabilities = new List<AttrGroupings>();

            for (int i = 0; i < cases.First().attributes.Count; i++)
                attrProbabilities.Add(new AttrGroupings(cases, i));

            var originalGroupings = cases.GroupBy(c => c.classification).ToList();
            if (originalGroupings.Count <= 25)
            {
                for (int i = 0; i < originalGroupings.Count; i++)
                {
                    double probability = (double)originalGroupings[i].Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1.
                    this.classProbabilities.Add(new ClassGrouping(originalGroupings[i].ToList(), this.attrProbabilities, probability));
                }
            }
            else
            {
                List<Case> temp = cases.OrderBy(c => c.classification).ToList();
                int takeCount = temp.Count / numOfGroupings;

                for (int i = 0; i < numOfGroupings; i++)
                {
                    List<Case> temp2;
                    if (i != numOfGroupings - 1) temp2 = temp.Skip(takeCount * i).Take(takeCount).ToList();
                    else temp2 = temp.Skip(takeCount * i).ToList();
                    double probability = (double)temp2.Sum(c => c.weight) / (double)cases.Sum(c => c.weight); // trenger egentlig ikke dele her, da sum av vekter er 1.
                    this.classProbabilities.Add(new ClassGrouping(temp2, this.attrProbabilities, probability));
                }
            }
        }
Example #15
0
        private static void Generate_Duplicated_ItemList(List<FileStruct> t, string output_filename)
        {
            try
            {
                List<FileStruct> duplicateItems = t
                                    .GroupBy(x => x.hash)
                                    .Where(x => x.Count() > 1)
                                    .SelectMany(x => x).ToList();

                if (duplicateItems.Any())
                {
                    StringBuilder builder = new StringBuilder();
                    using (FileStream file = File.Create(output_filename))
                    { }
                    foreach (var fss in duplicateItems)
                    {
                        builder.Append(fss.hash + " *" + fss.Name).AppendLine();
                    }
                    if (builder.Length > 0)
                    {
                        using (TextWriter writer = File.CreateText(output_filename))
                        {
                            writer.Write(builder.ToString());
                        }
                        builder.Clear();
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
 private static void Main()
 {
     var numberSequence = new List<int> { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 };
     var countDictionary = numberSequence.GroupBy(number => number)
         .ToDictionary(group => group.Key, group => group.Count());
     Console.WriteLine(string.Join(", ", numberSequence.Where(number => countDictionary[number] % 2 == 0)));
 }
        public static void Main()
        {
            var animals = new List<Animal>
            {
                new Dog("Sharo", 15, Gender.Male),
                new Dog("Karaman", 8, Gender.Male),
                new Frog("Kermit", 3, Gender.Male),
                new Frog("Froggy", 7, Gender.Female),
                new Tomcat("Tom", 14),
                new Tomcat("Garfield", 18),
                new Kitten("Kitty", 6),
                new Kitten("Mariika", 2)
            };

            animals.ToList().ForEach(Console.WriteLine);
            Console.WriteLine();

            animals
                .GroupBy(animal => animal.GetType().Name)
                .Select(group => new
                {
                    AnimalName = group.Key,
                    AverageAge = group.Average(a => a.Age)
                })
                .OrderByDescending(group => group.AverageAge)
                .ToList()
                .ForEach(group => Console.WriteLine($"{group.AnimalName}'s average age is: {group.AverageAge}"));
        }
Example #18
0
        static void Main(string[] args)
        {
            var list = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3 };

            var occurencesCount = list.GroupBy(x => x).ToDictionary(k => k.Key, v => v.Count());

            foreach (var pair in occurencesCount)
            {
                Console.WriteLine("Key{{{0}}} --> Value{{{1}}}", pair.Key, pair.Value);
            }

            // OR

            var buckets = new int[1000];

            foreach(var value in list)
            {
                buckets[value]++;
            }

            Console.WriteLine();

            for (int i = 0; i < buckets.Length; i++)
            {
                if (buckets[i] != 0)
                {
                    Console.WriteLine("Element: {0} --> {1} times.", i, buckets[i]);
                }
            }
        }
        static void Main()
        {

            Kitten Lili = new Kitten("Lili",2);
            Dog Sharo = new Dog("Sharo", 4, Gender.Male);
            Frog Frog = new Frog("Frog", 5, Gender.Female);
            Cat Jerry = new Cat("Jerry",7,Gender.Male);
            Tomcat Tom = new Tomcat("Tom", 3);
            Dog Pyhcho = new Dog("Pyhcho", 1, Gender.Male);
            List<Animal> animals = new List<Animal>() { Lili, Sharo, Frog, Tom,Pyhcho,Jerry };

            foreach (var animal in animals)
            {
                Console.WriteLine("{0}\n", animal);
            }

            animals
                .GroupBy(animal => animal.GetType().Name)
                .Select(group => new
                {
                    AnimalName = group.Key,
                    AverageAge = group.Average(a => a.Age)
                })
                .ToList()
                .ForEach(group => Console.WriteLine("{0} average age : {1}",group.AnimalName,group.AverageAge));
        }
        public static void OrderByTest()
        {
            Stopwatch stopWatch = new Stopwatch();
               List<Custom> customs = new List<Custom>();
               for (int i = 0; i < 2000000; i++)
               {
               customs.Add(new Custom() { Name = "Jack", Age = 21, Address = "NewYork" });
               customs.Add(new Custom() { Name = "Jime", Age = 26, Address = "China" });
               customs.Add(new Custom() { Name = "Tina", Age = 29, Address = "ShangHai" });
               customs.Add(new Custom() { Name = "Luo", Age = 30, Address = "Beijing" });
               customs.Add(new Custom() { Name = "Wang", Age = 60, Address = "Guangdong" });
               customs.Add(new Custom() { Name = "Feng", Age = 25, Address = "YunNan" });
               }

               stopWatch.Restart();
               var groupByAge = customs.GroupBy(item => item.Age).ToList();
               foreach (var item in groupByAge)
               {
               Console.WriteLine("Age={0},count = {1}", item.Key, item.Count());
               }
               stopWatch.Stop();

               Console.WriteLine("Linq group by time is: " + stopWatch.ElapsedMilliseconds);

               stopWatch.Restart();
               var lookupList = customs.ToLookup(i => i.Age);
               foreach (var item in lookupList)
               {
               Console.WriteLine("LookUP:Age={0},count = {1}", item.Key, item.Count());
               }
               stopWatch.Stop();
               Console.WriteLine("LookUp group by time is: " + stopWatch.ElapsedMilliseconds);
        }
        /// <summary>
        /// The compute.
        /// </summary>
        /// <param name="books">
        /// The books.
        /// </param>
        /// <param name="price">
        /// The price.
        /// </param>
        /// <returns>
        /// The <see cref="decimal"/>.
        /// </returns>
        public decimal Compute(List<Book> books, decimal price = 0)
        {
            if (!books.Any())
            {
                return price;
            }

            var groupBook = books.GroupBy(b => b.Tome).ToList();
            var nbGroup = groupBook.Count();
            if (nbGroup == 5 && groupBook.Count(g => g.Count() > 1) == 3)
            {
                nbGroup = 4;
                groupBook = groupBook.Take(nbGroup).ToList();
            }

            decimal reduction = this.reductions[nbGroup - 1];
            decimal totalPack = 0;
            groupBook.ForEach(
                group =>
                    {
                        var book = group.First();
                        books.Remove(book);
                        totalPack += book.Price;
                    });

            price += totalPack * reduction + this.Compute(books, price);
            return price;
        }
Example #22
0
        static void Main(string[] args)
        {
            List<Animal> animals = new List<Animal>();
            animals.Add(new Dog("Sharo",2,Gender.Male));
            animals.Add(new Dog("Peshko", 5, Gender.Male));
            animals.Add(new Cat("Kotka",3,Gender.Male));
            animals.Add(new Cat("Pisa", 12, Gender.Female));
            animals.Add(new Frog("Kyrmit",120,Gender.Male));
            animals.Add(new Kitten("Cherna kotka",5));
            animals.Add(new Tomcat("Bql kotarak",4));

            foreach (var animal in animals)
            {
                animal.ProduceSound();
            }

            animals
                .GroupBy(animal => animal.GetType().Name)
                .Select(group => new
                {
                    AnimalName = group.Key,
                    AverageAge = group.Average(a => a.Age)
                })
                .OrderByDescending(group => group.AverageAge)
                .ToList()
                .ForEach(group => Console.WriteLine($"{group.AnimalName}'s average age is: {group.AverageAge}"));
        }
Example #23
0
        public async Task PostBatchAsync(List<KafkaRecord> records)
        {
            try
            {
                foreach (var topicBatch in records.GroupBy(x => x.Topic))
                {
                    Console.WriteLine("POSTING: {0}, {1}", topicBatch.Count(), _producer.BufferCount);
                    var result = await _producer
                        .SendMessageAsync(topicBatch.Key, topicBatch.Select(x => x.Message), acks: 0, codec: MessageCodec.CodecGzip)
                        .ConfigureAwait(false);

                    if (result.Any(x => x.Error != (int)ErrorResponseCode.NoError))
                    {
                        Console.WriteLine("Some send messages failed to store.");
                    }
                    else
                    {
                        await SetStoredOffsetAsync(topicBatch.Key, topicBatch.Max(x => x.Offset)).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO need to signal a stop for the failed topic
                Console.WriteLine("Failed {0}", ex);
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the amouth of numbers you wish to work with: ");
            int y = int.Parse(Console.ReadLine());
            int[] arr = new int[y];
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine("Enter your number ");
                arr[i] = int.Parse(Console.ReadLine());
            }
            List<int> red = new List<int>(arr);

            var group = red.GroupBy(i => i);

            foreach (var item in group)
            {               
                Console.WriteLine("The number {0} occurs {1} times", item.Key, item.Count());
                if(y/2<item.Count())
                {
                    Console.WriteLine("The majorant is {0} ", item.Key); 
                }
                else
                {
                    Console.WriteLine("There is no majorant"); 
                }
            }        
        }
        public IEnumerable<VersionPair> GetVersionsToCompare(List<SemanticVersion> semverCompliantVersions)
        {

            var majorGroups = semverCompliantVersions.GroupBy(v => v.Version.Major);

            foreach (var major in majorGroups)
            {

                var minorGroups = major.GroupBy(v => v.Version.Minor).ToList();
                var left = minorGroups.First().Max();

                foreach (var minor in minorGroups)
                {
                    var right = minor.Max();

                    if (right == left)
                    {
                        continue;
                    }

                    yield return new VersionPair(left.Version.ToString(), right.Version.ToString());

                    left = right;
                }
            }
         
        }
Example #26
0
 public IEnumerable<Vote> GetVotes()
 {
     var votes =
         GetFundraisingPageDonations().Donations.Where(x => x.DonationDate >= new DateTime(2015, 04, 1)).ToList();
     var candidates = GetMovies();
     var result = new List<string>();
     foreach (var vote in votes)
     {
         if (!string.IsNullOrWhiteSpace(vote.Message))
         {
             var movie = IsMovie(vote.Message);
             result.Add(movie);
         }
     }
     var votesResults = new List<Vote>();
     foreach (var group in  result.GroupBy(x => x))
     {
         votesResults.Add(new Vote()
             {
                 Name = group.First(),
                 Votes = group.Count()
             });
     }
     return votesResults.Where(x => x.Name != "Empty");
 }
Example #27
0
        private int PreSum(List<Product> order)
        {
            //先將同類書籍分類
            var sameBookGroup = order
                .GroupBy(g => g.BookName);

            //把分類後的書籍加入索引值,再依索引值做為新的群組
            var bookList = sameBookGroup.Select(g => new
            {
                Value = g.Select((val, idx) => new
                {
                    Index = idx,
                    Value = val
                })
            }).SelectMany(g => g.Value.Select(v => new
            {
                Group = v.Index,
                Value = v.Value
            }));

            //把各群組計算總合
            var serialGroup = bookList
                .GroupBy(g => g.Group)
                .Select(g => new
                {
                    Count = g.Count(),
                    Sum = g.Sum(o => o.Value.Price)
                });

            return serialGroup.Sum(o => GetDiscount(o.Sum, o.Count));
        }
 public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs)
 {
   List<DefaultPackerPolicy.Entry> source1 = new List<DefaultPackerPolicy.Entry>();
   foreach (int importerInstanceId in textureImporterInstanceIDs)
   {
     TextureImporter textureImporter = EditorUtility.InstanceIDToObject(importerInstanceId) as TextureImporter;
     TextureFormat desiredFormat;
     ColorSpace colorSpace;
     int compressionQuality;
     textureImporter.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality);
     TextureImporterSettings dest = new TextureImporterSettings();
     textureImporter.ReadTextureSettings(dest);
     foreach (Sprite sprite in ((IEnumerable<UnityEngine.Object>) AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath)).Select<UnityEngine.Object, Sprite>((Func<UnityEngine.Object, Sprite>) (x => x as Sprite)).Where<Sprite>((Func<Sprite, bool>) (x => (UnityEngine.Object) x != (UnityEngine.Object) null)).ToArray<Sprite>())
       source1.Add(new DefaultPackerPolicy.Entry()
       {
         sprite = sprite,
         settings = {
           format = desiredFormat,
           colorSpace = colorSpace,
           compressionQuality = !TextureUtil.IsCompressedTextureFormat(desiredFormat) ? 0 : compressionQuality,
           filterMode = !Enum.IsDefined(typeof (UnityEngine.FilterMode), (object) textureImporter.filterMode) ? UnityEngine.FilterMode.Bilinear : textureImporter.filterMode,
           maxWidth = 2048,
           maxHeight = 2048,
           generateMipMaps = textureImporter.mipmapEnabled,
           enableRotation = this.AllowRotationFlipping,
           allowsAlphaSplitting = textureImporter.GetAllowsAlphaSplitting(),
           paddingPower = !textureImporter.mipmapEnabled ? (uint) EditorSettings.spritePackerPaddingPower : 3U
         },
         atlasName = this.ParseAtlasName(textureImporter.spritePackingTag),
         packingMode = this.GetPackingMode(textureImporter.spritePackingTag, dest.spriteMeshType),
         anisoLevel = textureImporter.anisoLevel
       });
     Resources.UnloadAsset((UnityEngine.Object) textureImporter);
   }
   foreach (IGrouping<string, DefaultPackerPolicy.Entry> source2 in source1.GroupBy<DefaultPackerPolicy.Entry, string, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, string>) (e => e.atlasName), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (e => e)))
   {
     int num = 0;
     IEnumerable<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>> source3 = source2.GroupBy<DefaultPackerPolicy.Entry, AtlasSettings, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, AtlasSettings>) (t => t.settings), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (t => t));
     foreach (IGrouping<AtlasSettings, DefaultPackerPolicy.Entry> grouping in source3)
     {
       string key1 = source2.Key;
       if (source3.Count<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>>() > 1)
         key1 += string.Format(" (Group {0})", (object) num);
       AtlasSettings key2 = grouping.Key;
       key2.anisoLevel = 1;
       if (key2.generateMipMaps)
       {
         foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping)
         {
           if (entry.anisoLevel > key2.anisoLevel)
             key2.anisoLevel = entry.anisoLevel;
         }
       }
       job.AddAtlas(key1, key2);
       foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping)
         job.AssignToAtlas(key1, entry.sprite, entry.packingMode, SpritePackingRotation.None);
       ++num;
     }
   }
 }
Example #29
0
        void assetsControlLoad(object sender, EventArgs e)
        {
            if( Helper.IsInDesignMode )
            {
                return ;
            }

            var extensibility = ObjectFactory.GetInstance<IExtensibility>( ) ;
            var imageRepository=ObjectFactory.GetInstance<IImageRepository>( ) ;

            _imageList = imageRepository.CreateImageList( ) ;
            uiList.SmallImageList = _imageList ;

            var plugins = new List<IPlugin>();

            plugins.AddRange( extensibility.EditorPlugins );
            plugins.AddRange( extensibility.BehaviourPlugins );

            plugins.ForEach( p => imageRepository.Set( p.Icon ) );

            plugins.GroupBy( p => p.CategoryName ).Distinct( ).ForEach(
                grouping => _pluginsForCategories.Add( grouping.Key, new List<IPlugin>( ) ) ) ;

            plugins.ForEach( p=> _pluginsForCategories[p.CategoryName].Add( p ) );

            XElement xml = buildXml( ) ;

            populateTreeFromXml( xml ) ;
        }
Example #30
0
        static void Main()
        {
            List<Person> l=new List<Person>();
            string input = Console.ReadLine();
            while (!input.Equals("END"))
            {

                string[] pars = input.Split(' ');
                string name = pars[0] + " " +pars[1];
                int group = int.Parse(pars[2]);

                l.Add(new Person(name,group));

                input = Console.ReadLine();
            }

            var grouped=l.GroupBy(x => x.Group,
                x => x.Name,
                (group, name) => new
                {
                    Group = group,
                    Name = name.ToList(),
                }
                );
            foreach (var gr in grouped.OrderBy(x=>x.Group))
            {
                Console.WriteLine("{0} - {1}",gr.Group,string.Join(", ",gr.Name));
            }
        }