Ejemplo n.º 1
1
        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();
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
0
        public static Results CompareFiles(List <FileData> files)
        {
            var res       = new Results();
            var sameNames = files?.GroupBy(fd => fd.FileName).Where(group => group.Count() > 1);

            if (sameNames != null)
            {
                foreach (var sameName in sameNames)
                {
                    res.SameNames.Add(new ObservableCollection <FileData>(sameName.ToList()));
                }
            }
            else
            {
                Debug.WriteLine("No same names");
            }
            var sameSizes = files?.GroupBy(fd => fd.Size).Where(group => group.Count() > 1);

            if (sameSizes != null)
            {
                foreach (var sameSize in sameSizes)
                {
                    res.SameSizes.Add(new ObservableCollection <FileData>(sameSize.ToList()));
                }
            }
            else
            {
                Debug.WriteLine("No same sizes");
            }

            return(res);
        }
Ejemplo n.º 4
0
        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()));
        }
Ejemplo n.º 5
0
        public IActionResult Index()
        {
            LoadResults();
            IEnumerable <IGrouping <string, Matches> > matchesGroup = _matchesList?.GroupBy(x => x.MatchTypeName);

            return(View(matchesGroup));
        }
        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());
            }
        }
Ejemplo n.º 7
0
 public List <dynamic> GetClientesFies()
 => _compras?.GroupBy(compra => compra.Cliente)
 ?.Select(compra =>
 {
     dynamic obj           = new ExpandoObject();
     obj.cliente           = compra.Key;
     obj.quantidadeCompras = compra.Count();
     return(obj);
 })
 ?.OrderByDescending(obj => obj.quantidadeCompras)
 ?.ToList();
        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();
        }
Ejemplo n.º 9
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();
    }
Ejemplo n.º 10
0
        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

                    }

                }
        }
Ejemplo n.º 11
0
        public Dictionary <string, Dictionary <string, decimal?[][]> > BuildEASDictionary(List <EasFundingLine> easFundingLines, string sofCode)
        {
            int.TryParse(sofCode, out var sofCodeInt);

            return(easFundingLines?
                   .GroupBy(fl => fl.FundLine, StringComparer.OrdinalIgnoreCase)
                   .ToDictionary(k => k.Key,
                                 v => v.SelectMany(ld => ld.EasSubmissionValues)
                                 .GroupBy(easv => easv.AdjustmentTypeName, StringComparer.OrdinalIgnoreCase)
                                 .ToDictionary(k => k.Key, value =>
                                               value?.Select(pvGroup => new decimal?[]
            {
                GetPeriodValue(pvGroup.Period1, sofCodeInt),
                GetPeriodValue(pvGroup.Period2, sofCodeInt),
                GetPeriodValue(pvGroup.Period3, sofCodeInt),
                GetPeriodValue(pvGroup.Period4, sofCodeInt),
                GetPeriodValue(pvGroup.Period5, sofCodeInt),
                GetPeriodValue(pvGroup.Period6, sofCodeInt),
                GetPeriodValue(pvGroup.Period7, sofCodeInt),
                GetPeriodValue(pvGroup.Period8, sofCodeInt),
                GetPeriodValue(pvGroup.Period9, sofCodeInt),
                GetPeriodValue(pvGroup.Period10, sofCodeInt),
                GetPeriodValue(pvGroup.Period11, sofCodeInt),
                GetPeriodValue(pvGroup.Period12, sofCodeInt),
            }).ToArray() ?? Array.Empty <decimal?[]>(),
                                               StringComparer.OrdinalIgnoreCase),
                                 StringComparer.OrdinalIgnoreCase)
                   ?? new Dictionary <string, Dictionary <string, decimal?[][]> >());
        }
        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;
        }
Ejemplo n.º 13
0
        private void btnReturn_Click(object sender, RoutedEventArgs e)
        {
            dynamic row = lvPurchase.SelectedItem;

            List <StockModel> stocks = controller.GetStocksByPurchaseId(row.PurchaseId);
            var  purchaseReturns     = stocks?.GroupBy(z => new { z.ProductCode, z.BatchNo }).Select(x => new PurchaseReturnModel(null, x.FirstOrDefault().PurchaseOrderId.Value, x.FirstOrDefault().ProductCode, x.FirstOrDefault().BatchNo, x.Sum(y => y.Quantity), UserModelVm.UserId, CommonFunctions.ParseDateToFinclave(DateTime.Now.ToShortDateString()), string.Empty)).ToList();
            bool isSaved             = controller.SaveUpdatePurchaseReturns(purchaseReturns);

            if (isSaved)
            {
                var result = controller.UpdateStatus(row, (int)CommonEnum.PurchaseStatus.FullyReturned);

                //if (result == true)
                //{
                List <PurchaseOrderModel> lstPurchase = controller.GetPurchase().ToList();
                if (lstPurchase.Any())
                {
                    _purchase = lstPurchase;
                    lvPurchase.ItemsSource = _purchase;
                    //   ConfirmationPopup form1 = new ConfirmationPopup((string)myResourceDictionary["purchase_retunedmsg"], "Purchase", false);
                    //  form1.ShowDialog();
                    Common.Notification((string)myResourceDictionary["purchase_retunedmsg"], header, false);
                    ButtonDisable();
                }
                else
                {
                    //  ConfirmationPopup form2 = new ConfirmationPopup(responce.FaultData.Detail.ErrorDetails, header, false);
                    //    form2.ShowDialog();
                }
            }
        }
Ejemplo n.º 14
0
        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);
        }
        private IDictionary <string, Dictionary <string, Dictionary <int, List <EasPaymentValue> > > > BuildEasDictionary(List <EasSubmissionDecodedValue> easSubmissionDecodedValues)
        {
            var sofDictionary =
                easSubmissionDecodedValues
                .GroupBy(x => new { x.FundingLine, x.AdjustmentName, x.PaymentName, x.Period, x.PaymentValue })
                .ToDictionary(
                    k => k.Key,
                    v => v.Select(s => s.DevolvedAreaSof).ToList());

            return(easSubmissionDecodedValues?
                   .GroupBy(c => c.FundingLine, StringComparer.OrdinalIgnoreCase)
                   .ToDictionary(
                       fundingLine => fundingLine.Key,
                       fundingLineValues => fundingLineValues.Select(flv => flv)
                       .GroupBy(p => p.PaymentName, StringComparer.OrdinalIgnoreCase)
                       .ToDictionary(
                           paymentName => paymentName.Key,
                           paymentNameValue => paymentNameValue
                           .GroupBy(p => p.Period)
                           .ToDictionary(
                               k3 => k3.Key,
                               v3 => v3.Select(
                                   eas => new EasPaymentValue(
                                       eas.PaymentValue, eas.DevolvedAreaSof == -1 ? null : (int?)eas.DevolvedAreaSof)).ToList()),
                           StringComparer.OrdinalIgnoreCase),
                       StringComparer.OrdinalIgnoreCase));
        }
        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));
        }
Ejemplo n.º 17
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]);
                }
            }
        }
Ejemplo n.º 18
0
        public ActionResult SearchBookings(RequestSearchBookings request)
        {
            var supplier = _usersManagementService.GetActiveCustomer(HttpContext);

            if (supplier == null)
            {
                return(Json(new { resultSearchBookings = string.Empty }));
            }

            DateTime fromDateTime;
            DateTime toDateTime;

            var result = new List <SearchBookingsDto>();

            if (DateTime.TryParse(request.FromDate, out fromDateTime) && DateTime.TryParse(request.ToDate, out toDateTime))
            {
                if ((toDateTime - fromDateTime).TotalDays <= 7)
                {
                    result = _bokaRepository.SearchBookings(request);
                }
            }

            var groupBookings = result?
                                .GroupBy(m => new { m.FromDate })
                                .ToDictionary(s => s.Key.FromDate, t => t.ToList());

            return(PartialView("~/Views/Boka/_TableSearchBookingResult.cshtml", groupBookings));
        }
Ejemplo n.º 19
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");
        }
Ejemplo n.º 20
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}"));
        }
Ejemplo n.º 21
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 ) ;
        }
 private static List <NumberCount> Original1(List <int> integers)
 {
     return(integers?.GroupBy(number => number)
            .OrderByDescending(group => group.Count())
            .Select(k => new NumberCount(k.Key, k.Count()))
            .ToList());
 }
Ejemplo n.º 23
0
        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);
                    }

                }
            }
Ejemplo n.º 24
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));
        }
Ejemplo n.º 25
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);
            }
        }
 private static List <NumberCount> Original2(List <int> integers)
 {
     return(integers?.GroupBy(number => number)
            .Select(k => new NumberCount(k.Key, k.Count()))
            .OrderByDescending(x => x.Occurrences)
            .ToList());
 }
Ejemplo n.º 27
0
        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"); 
                }
            }        
        }
 //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);
     }
 }
Ejemplo n.º 29
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));
                }
            }
        }
Ejemplo n.º 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));
            }
        }
 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}"));
        }
        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;
                }
            }
         
        }
Ejemplo n.º 34
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");
 }
        /// <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));
        }
Ejemplo n.º 36
0
        /// <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;
        }
        public static void Main()
        {
            List<Student> students = new List<Student>();
            Student ivan = new Student("Ivan", "Ivanov", "141000", "02325123", "*****@*****.**", 1);
            students.Add(ivan);
            Student gosho = new Student("Gosho", "Goshev", "141001", "052222222", "*****@*****.**", 1);
            students.Add(gosho);
            Student pesho = new Student("Pesho", "Mastikata", "141002", "052123634", "*****@*****.**", 2);
            students.Add(pesho);
            Student kiro = new Student("Kiro", "Leshnikov", "141003", "03225123", "*****@*****.**", 2);
            students.Add(kiro);
            Student maria = new Student("Maria", "Dimitrova", "141004", "056251231", "*****@*****.**", 3);
            students.Add(maria);
            Student vanq = new Student("Vanq", "Ivanova", "141005", "032412413", "*****@*****.**", 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);
            }
        }
Ejemplo n.º 38
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;
            }
        }
 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;
     }
   }
 }
 public Dictionary <string, Dictionary <string, decimal?[][]> > BuildEASDictionary(List <EasFundingLine> easFundingLines)
 {
     return(easFundingLines?
            .GroupBy(fl => fl.FundLine, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(k => k.Key,
                          v => v.SelectMany(ld => ld.EasSubmissionValues)
                          .GroupBy(easv => easv.AdjustmentTypeName, StringComparer.OrdinalIgnoreCase)
                          .ToDictionary(k => k.Key, value =>
                                        value.Select(pvGroup => new decimal?[]
     {
         pvGroup.Period1?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period2?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period3?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period4?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period5?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period6?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period7?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period8?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period9?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period10?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period11?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
         pvGroup.Period12?.Where(s => s.DevolvedAreaSofs == null).Sum(x => x.PaymentValue),
     }).ToArray(),
                                        StringComparer.OrdinalIgnoreCase),
                          StringComparer.OrdinalIgnoreCase)
            ?? new Dictionary <string, Dictionary <string, decimal?[][]> >());
 }
 private static List <NumberCount> AsParallel1(List <int> integers)
 {
     return(integers?.GroupBy(number => number)
            .AsParallel()                                   //each group will be count by a CPU unit
            .Select(k => new NumberCount(k.Key, k.Count())) //Grap result, before sort
            .OrderByDescending(x => x.Occurrences)          //sort after result
            .ToList());
 }
Ejemplo n.º 42
0
        public JsonResult ShopCount(string Regions, string ShopBusinessType, string ShopServices, string ShopTechLevel)
        {
            Dictionary <string, object> dic = new Dictionary <string, object>();

            if (string.IsNullOrWhiteSpace(Regions))
            {
                dic.Add("Succeed", "False");
                dic.Add("Message", "请选择地区!");
                return(Json(dic));
            }
            if (string.IsNullOrWhiteSpace(ShopBusinessType))
            {
                dic.Add("Succeed", "False");
                dic.Add("Message", "请选择门店类型!");
                return(Json(dic));
            }
            if (string.IsNullOrWhiteSpace(ShopServices))
            {
                dic.Add("Succeed", "False");
                dic.Add("Message", "请选择门店服务!");
                return(Json(dic));
            }
            if (string.IsNullOrWhiteSpace(ShopTechLevel))
            {
                dic.Add("Succeed", "False");
                dic.Add("Message", "请选择门店等级!");
                return(Json(dic));
            }

            try
            {
                List <Shop> result = GetShop(Regions, ShopBusinessType, ShopServices, ShopTechLevel);

                List <IGrouping <string, Shop> > group = result?.GroupBy(x => x.City).ToList();
                List <Shop> result1 = new List <Shop>();
                if (group != null && group.Any())
                {
                    foreach (IGrouping <string, Shop> item in group)
                    {
                        Shop model = item.FirstOrDefault();
                        model.TotalCount = item.Count();
                        result1.Add(model);
                    }
                }
                dic.Add("Succeed", "True");
                dic.Add("Message", result1);
                return(Json(dic));
            }
            catch
            {
                dic.Add("Succeed", "False");
                dic.Add("Message", "服务器错误");
                return(Json(dic));
            }
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Assuming the information in the data provided is complete and accurate,
        /// generate a report that shows any errors(negative cash balances,
        /// negative share balance) by investor.
        /// </summary>
        /// <param name="transactions">Transaction list value generated from CSVParser</param>
        /// <returns>IEnumerable<BreakViewModel> used as viewmodel for Break View.</returns>
        public static IEnumerable <BreakViewModel> BreakReport(List <TransactionModel> transactions)
        {
            var result = transactions?.GroupBy(x => x.InvestorName).Select(x => new BreakViewModel
            {
                InvestorName    = x.Key,
                NetCashBalance  = x.Sum(y => y.TotalSaleSigned),
                NetShareBalance = x.Sum(y => y.SharesAmountSigned)
            }).Where(x => x.NetCashBalance < 0 || x.NetShareBalance < 0);

            return(result);
        }
Ejemplo n.º 44
0
        private static AccountAgreementType GetAgreementType(List <AgreementType> agreementTypes)
        {
            var agreementTypeGroup = agreementTypes?.GroupBy(x => x).OrderByDescending(x => x.Key);

            if (agreementTypeGroup == null || !agreementTypeGroup.Any())
            {
                return(AccountAgreementType.Unknown);
            }

            return((AccountAgreementType)Enum.Parse(typeof(AccountAgreementType), agreementTypeGroup?.FirstOrDefault()?.Key.ToString()));
        }
        public List <ReceiveTotalReportDetail> GenerateSummary(List <ReceiveReportDetail> reportDetails)
        {
            var transactionsByCurrency = reportDetails?.GroupBy(tran => new { tran.Currency, tran.TransactionType });

            return(transactionsByCurrency?.Select(currencyGroup => new ReceiveTotalReportDetail
            {
                TransactionType = currencyGroup.Key.TransactionType,
                Count = currencyGroup.Count(),
                Currency = currencyGroup.Key.Currency,
                TotalAmount = currencyGroup.Select(tran => tran.TotalAmount).Sum()
            }).ToList());
        }
Ejemplo n.º 46
0
        /// <summary>
        /// For each Investor and Fund, return net profit or loss on investment.
        /// </summary>
        /// <param name="transactions">Transaction list value generated from CSVParser</param>
        /// <returns>IEnumerable<InvestorViewModel> used as viewmodel for Investor View.</returns>
        public static IEnumerable <InvestorViewModel> InvestorProfit(List <TransactionModel> transactions)
        {
            var result = transactions?.GroupBy(x => new { x.InvestorName, x.FundDescription })
                         .Select(x => new InvestorViewModel
            {
                InvestorName    = x.Key.InvestorName,
                FundDescription = x.Key.FundDescription,
                TotalSigned     = x.Sum(y => y.TotalSaleSigned)
            });

            return(result);
        }
Ejemplo n.º 47
0
 //Group the pets based on the gender for any pet name
 public List <GroupedPetVm> GroupPets(List <PersonDto> personDto, string petType)
 {
     return(personDto?
            .GroupBy(p => p.Gender)
            .Select(vm => new GroupedPetVm
     {
         Gender = vm.Key,
         PetNames = vm.SelectMany(p => p.Pets)
                    .Where(pet => string.Compare(pet.Type, petType, StringComparison.CurrentCultureIgnoreCase) == 0)
                    .OrderBy(q => q.Name)
                    .Select(r => r.Name).ToList()
     }).ToList());
 }
Ejemplo n.º 48
0
        public static IEnumerable <AveragePricePerCity> ConvertToAveragePricePerCities(this List <Announce> announces, bool sortAsc)
        {
            var avgPricesPerCity = announces?.GroupBy(
                a => a.City,
                a => a.PricePerSquareMeter)
                                   .Select(ac => new AveragePricePerCity()
            {
                City         = ac.Key,
                AveragePrice = ac.Average() ?? 0
            })
                                   .Sort(sortAsc);

            return(avgPricesPerCity);
        }
        public ResultOperation Update(string name, bool isActive, List <MessageTypeParamsModel> paramsXML)
        {
            paramsXML = paramsXML?.Where(c => !string.IsNullOrWhiteSpace(c.Name)).ToList();
            ResultOperation resultOperation = new ResultOperation();

            this.Name      = name;
            this.IsActive  = isActive;
            this.ParamsXML = paramsXML.BuildXml() ?? "";
            if (paramsXML?.GroupBy(c => c.Name).Any(c => c.Count() > 1) ?? false)
            {
                resultOperation.AddError(LangUtility.Get("SameName.Text", nameof(sysBpmsMessageType)));
            }
            return(resultOperation);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// For each Sales Rep, generate a summary of the net amount held by investors across all funds.
        /// </summary>
        /// <param name="transactions">Transaction list value generated from CSVParser</param>
        /// <returns>IEnumerable<ManagementViewModel> used as viewmodel for Management View.</returns>
        public static IEnumerable <ManagementViewModel> ManagementSummary(List <TransactionModel> transactions)
        {
            var result = transactions?.GroupBy(x => x.SalesRepName).Select(x => new ManagementViewModel
            {
                SalesRepName = x.Key,
                Details      = x.GroupBy(y => y.InvestorName).Select(y => new ManagementDetailViewModel
                {
                    InvestorName = y.Key,
                    TotalAmount  = y.Sum(z => z.TotalSaleSigned)
                })
            });

            return(result);
        }
Ejemplo n.º 51
0
        private void btnReturn_Click(object sender, RoutedEventArgs e)
        {
            dynamic           row    = lvPurchase.SelectedItem;
            List <StockModel> stocks = controller.GetStocksByPurchaseId(row.PurchaseId);
            var purchaseReturns      = stocks?.GroupBy(z => new { z.ProductCode, z.BatchNo }).Select(x => new PurchaseReturnModel(null, x.FirstOrDefault().PurchaseOrderId.Value, x.FirstOrDefault().ProductCode, x.FirstOrDefault().BatchNo, x.Sum(y => y.Quantity), UserModelVm.UserId, CommonFunctions.ParseDateToFinclave(DateTime.Now.ToShortDateString()), string.Empty)).ToList();

            if (controller.SaveUpdatePurchaseReturns(purchaseReturns))
            {
                controller.UpdateStatus(row, (int)CommonEnum.PurchaseStatus.FullyReturned);
                BindDirectPurchases();
                Common.Notification((string)myResourceDictionary["purchase_retunedmsg"], header, false);
                ButtonDisable();
            }
        }
Ejemplo n.º 52
0
        private List <EmployeeModel> FormOutputData(List <EmployeeModel> employees)
        {
            var grEmployees = employees?.GroupBy(e => e.Id, e => e.Professions).ToList();

            var mappedEmployees = grEmployees?.Join(employees, g => g.Key, e => e.Id, (g, e) => new EmployeeModel
            {
                Age         = e.Age,
                FirstName   = e.FirstName,
                Gender      = e.Gender,
                Id          = e.Id,
                LastName    = e.LastName,
                Professions = g.SelectMany(col => col).ToList()
            });

            return(mappedEmployees?.Unique(m => m.Id).ToList());
        }
Ejemplo n.º 53
0
        private void AddChildrenToTrace(DottyTrace trace, List <DottySpan> dottySpans, List <DottyLogLine> dottyLogLines)
        {
            var logsLookup = dottyLogLines?.GroupBy(l => l.DottySpanId).ToDictionary(l => l.Key, l => l.ToList());
            var lookup     = new Dictionary <long, DottySpan>();
            // head is with no parent
            var parent = dottySpans.Single(s => !s.DottySpanId.HasValue);

            lookup[parent.Id] = parent;
            foreach (var span in dottySpans.Where(s => s.DottySpanId.HasValue).OrderBy(x => x.DottySpanId))
            {
                lookup[parent.Id].ChildSpans.Add(span);
                lookup[span.Id] = span;

                span.Logs = logsLookup?.GetValueOrDefault(span.Id);
            }
        }
Ejemplo n.º 54
0
        private int ProcessEntries(List <Dictionary <string, string> > entries)
        {
            var points = 0;

            if (entries == null)
            {
                return(0);
            }
            foreach (var grp in entries?.GroupBy(entry => String.Join(";", groupByColumns.Select(col => $"{col}={entry[col]}"))))
            {
                if (grp.Count() >= MinHits)
                {
                    var entry  = grp.FirstOrDefault();
                    var result = new OutputRecord();
                    result.Time = DateTime.FromBinary(long.Parse(entry["Time"]));
                    if (OutTimeInUTC.ToBool())
                    {
                        result.Time = result.Time.ToUniversalTime();
                    }
                    result.HostName = HostName;
                    foreach (var col in groupByColumns)
                    {
                        result.GroupedColumns.Add(col, entry[col]);
                    }

                    foreach (var metric in aggregateMap)
                    {
                        foreach (var aggr in metric.Value)
                        {
                            result.AggregatedColumns.Add(aggr, ProcessValues(grp.Select(g => g[aggr.ColumnName]), aggr));
                        }
                    }
                    foreach (var metric in calculatedColumns)
                    {
                        var formula = metric.Formula.ToLower();
                        foreach (var aggr in result.AggregatedColumns)
                        {
                            formula = formula.Replace($"[{aggr.Key.ColumnName.ToLower()}:{aggr.Key.Formula}]", aggr.Value.ToString());
                        }
                        result.CalculatedColumns.Add(metric, EvaluateFormula(formula));
                    }
                    resultEntries.Enqueue(result);
                    points++;
                }
            }
            return(points);
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Gets the majority vote labels, indexed by tweet Id.
 /// </summary>
 /// <param name="crowdLabels">
 /// The crowd labels.
 /// </param>
 /// <returns>
 /// The majority label keyed by tweet id.
 /// </returns>
 public static Dictionary <string, int> MajorityVoteLabels(List <CrowdDatum> crowdLabels)
 {
     return(crowdLabels?.GroupBy(d => d.TweetId).ToDictionary(
                t => t.Key,
                t => t.GroupBy(d => d.WorkerLabel)
                .Select(g => new { label = g.Key, count = g.Count() })).ToDictionary(
                kvp => kvp.Key,
                kvp =>
     {
         var max = kvp.Value.Max(a => a.count);
         var majorityLabs = kvp.Value.Where(a => a.count == max).Select(a => a.label).ToArray();
         var index = (majorityLabs.Length > 1)
                                 ? 0
                                 : Rand.Int(majorityLabs.Length);
         return majorityLabs[index];
     }));
 }
Ejemplo n.º 56
0
        /// <summary>
        /// For each Sales Rep, generate Year to Date, Month to Date, Quarter to
        /// Date, and Inception to Date summary of cash amounts sold across all funds.
        /// </summary>
        /// <param name="transactions">Transaction list value generated from CSVParser</param>
        /// <returns>IEnumerable<SalesViewModel> used as viewmodel for Sales View.</returns>
        public static IEnumerable <SalesViewModel> SalesSummary(List <TransactionModel> transactions)
        {
            var currentYear    = DateTime.Today.Year;
            var currentMonth   = DateTime.Today.Month;
            var currentQuarter = (currentMonth + 2) / 3;

            var result = transactions?.GroupBy(x => x.SalesRepName).Select(x => new SalesViewModel
            {
                SalesRepName    = x.Key,
                YearToDate      = x.Where(y => y.TransactionDate.Year == currentYear).Sum(y => y.TotalSale),
                MonthToDate     = x.Where(y => y.TransactionDate.Month == currentMonth).Sum(y => y.TotalSale),
                QuarterToDate   = x.Where(y => y.QuarterNumber == currentQuarter).Sum(y => y.TotalSale),
                InceptionToDate = x.Sum(y => y.TotalSale)
            });

            return(result);
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Saves specified delivery details.
        /// </summary>
        /// <param name="manufacturer">Object of the manufacturer</param>
        /// <param name="materialItems">List of the Material Items</param>
        /// <returns>Manufacturer</returns>
        public Manufacturer SaveDelivery(Manufacturer manufacturer, List <MaterialItems> materialItems)
        {
            using (_loggerFactory.CreateMethodLogger(MethodBase.GetCurrentMethod(), _logger))
            {
                using (var context = _dbContextFactory.CreateDbContext())
                {
                    if (manufacturer != null)
                    {
                        var delivery = new Delivery()
                        {
                            DeliveryDate = DateTime.Now
                        };
                        context.SaveDeliveryDetails(delivery);

                        if (delivery != null)
                        {
                            var itemDetails = materialItems?.GroupBy(x => x.ItemId)
                                              .Select(item =>
                            {
                                var returnQTY      = item.First();
                                returnQTY.Quantity = item.Sum(xt => xt.Quantity);
                                return(returnQTY);
                            }).ToList();

                            itemDetails?.ForEach(item =>
                            {
                                var deliveryDetails = new DeliveryDetails()
                                {
                                    DeliveryId   = delivery.DeliveryId,
                                    DeliveryDate = DateTime.Now,
                                    ItemId       = item.ItemId,
                                    Quantity     = item.Quantity
                                };

                                context.SaveDeliveryDetails(deliveryDetails);
                            });
                        }

                        context.SaveChanges();
                    }

                    return(manufacturer);
                }
            }
        }
Ejemplo n.º 58
0
        public async Task WeatherCheck(UTMService utmService)
        {
            List <Flight> flights = await utmService.Operation.GetFlightsInAllOperationsAsync();

            var distinctFlights = flights?.GroupBy(flight => flight.uas.uniqueIdentifier).Select(uas => uas.First()).ToList();

            distinctFlights?.ForEach(async flight =>
            {
                var flightCoordinates = flight.coordinate;
                var weatherResponse   = await _weatherService.GetWeatherAtCoord(latitude: flightCoordinates.latitude.ToString(), longitude: flightCoordinates.longitude.ToString());
                var process           = new Process();
                var key           = $"{flight.uasOperation}-{flight.uas.uniqueIdentifier}-weather";
                var cachedProcess = await _redisService.Get <State>(key);
                if (cachedProcess != null)
                {
                    process.CurrentState = cachedProcess.CurrentState;
                }
                else
                {
                    cachedProcess = new State();
                }

                var validatedRule = _weatherRule.ValidateRule(weatherResponse);
                if (!validatedRule.Success && (process.CurrentState == ProcessState.Active || process.CurrentState == ProcessState.Inactive))
                {
                    process.MoveNext();
                }
                else
                {
                    process.MovePrev();
                }

                if (process.CurrentState == ProcessState.Raised && !cachedProcess.Triggered && !cachedProcess.Handled)
                {
                    cachedProcess.Triggered = true;
                    await SendAlert(new Alert {
                        droneId = flight.uas.uniqueIdentifier, type = "weather-alert", reason = validatedRule.Message
                    });
                }
                cachedProcess.CurrentState = process.CurrentState;
                await _redisService.Set(key, cachedProcess);
            });
        }
Ejemplo n.º 59
0
        /// <summary>
        /// Returns all User to Role mappings and adds cascade roles for specific roles
        /// </summary>
        /// <param name="adaptorUserUserRoles"></param>
        /// <returns></returns>
        private static IEnumerable <AdaptorUserUserRole> GetAllUserRoles(List <AdaptorUserUserRole> adaptorUserUserRoles)
        {
            foreach (var userRoleGroup in adaptorUserUserRoles?.GroupBy(x => x.AdaptorUserId))
            {
                var userRoles = userRoleGroup.ToList();
                if (IsRoleInCollection(userRoles, UserRoleType.Administrator))
                {
                    CheckAndAddUserUserRole(userRoles, UserRoleType.Maintainer, adaptorUserUserRoles);
                    CheckAndAddUserUserRole(userRoles, UserRoleType.Reporter, adaptorUserUserRoles);
                    CheckAndAddUserUserRole(userRoles, UserRoleType.Submitter, adaptorUserUserRoles);
                }

                if (IsRoleInCollection(userRoles, UserRoleType.Submitter))
                {
                    CheckAndAddUserUserRole(userRoles, UserRoleType.Reporter, adaptorUserUserRoles);
                }
            }
            return(adaptorUserUserRoles);
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Get Values for particular? attribute(s)(Member Variable(s)) of an Entity(Class) from Context Table.
        /// </summary>
        /// <param name="query">IQueryable of DbSet of type of DbContext</param>
        /// <param name="properties">The (;) semi-colon separated string of Selected Properties for EntityType</param>
        /// <param name="properties"></param>
        async Task <ICollection <PropertyData> > ILocalizationRepository.GetPropertyValueForAttribute(IQueryable query, string properties)
        {
            if (string.IsNullOrWhiteSpace(properties))
            {
                return(null);
            }
            ICollection <PropertyData> _properties = new List <PropertyData>();

            if (query != null)
            {
                var selectProps = properties.Split(';');
                for (int i = 0; i < selectProps?.Length; i++)
                {
                    var prop = selectProps[i];
                    if (!string.IsNullOrWhiteSpace(prop))
                    {
                        var objects = query?.Select(prop).Distinct();
                        if (objects != null)
                        {
                            var j             = 0;
                            var _propertyData = new PropertyData()
                            {
                                Id = i, PropertyName = prop, PropertyValues = new List <PropertyValue>()
                            };
                            foreach (var item in objects)
                            {
                                j++;
                                if (item != null)
                                {
                                    _propertyData.PropertyValues.Add(new PropertyValue((i * 10000) + j, item.ToString(), item.ToString()));
                                }
                            }
                            _properties.Add(_propertyData);
                        }
                    }
                }
            }

            _properties?.GroupBy(p => p.PropertyName); // Group property by Name
            return(_properties);
        }