Example #1
0
        public void OfTypeClause()
        {
            //OfType operator filters the collection based on the ability to cast to a specific type
            IList mixedList = new ArrayList();
            mixedList.Add(0);
            mixedList.Add("One");
            mixedList.Add("Two");
            mixedList.Add(3);
            mixedList.Add(new Student
            {
                StudentId    = 1,
                StudentName = "Bill"
            });

            //output string ony
            var stringResult = from s in mixedList.OfType<string>()
                select s;
            //One
            //Two
            var studentOut = from s in mixedList.OfType<Student>()
                select s;

            var mthod = mixedList.OfType<Student>().ToList();

            foreach (var student in mthod)
            {
                Console.WriteLine(student.StudentName);
            }
        }
 public void M5(ArrayList list)
 {
     foreach (A i in list.OfType<A>()) // Noncompliant
     { }
     foreach (var i in list)
     { }
     foreach (object i in list)
     { }
     foreach (B i in list.OfType<B>()) // Noncompliant
     { }
 }
        public static Mock<IDataParameterCollection> CreateIDataParameterCollection(this MockRepository repository)
        {
            var list = new ArrayList(); // ArrayList more closely matches IDataParameterCollection.
            var parameters = repository.Create<IDataParameterCollection>();

            parameters.Setup(p => p.Add(It.IsAny<IDataParameter>())).Returns((IDataParameter p) => list.Add(p));
            parameters.Setup(p => p.Contains(It.IsAny<string>())).Returns((string n) => list.OfType<IDataParameter>().Any(p => p.ParameterName == n));
            parameters.Setup(p => p[It.IsAny<int>()]).Returns((int i) => list[i]);
            parameters.Setup(p => p[It.IsAny<string>()]).Returns((string n) => list.OfType<IDataParameter>().FirstOrDefault(p => p.ParameterName == n));
            parameters.Setup(p => p.Count).Returns(() => list.Count);

            return parameters;
        }
Example #4
0
        static void LINQOverArrayList()
        {
            Console.WriteLine("***** LINQ over ArrayList *****");

            // Here is a nongeneric collection of cars.
            ArrayList myCars = new ArrayList() {
                new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
                new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
                new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
                new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
                new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"}
              };

            // Transform ArrayList into an IEnumerable<T>-compatible type.
            var myCarsEnum = myCars.OfType<Car>();

            // Create a query expression.
            //var fastCars = from c in myCarsEnum where c.Speed > 55 select c;
            var fastCars = myCarsEnum.Where(c => c.Speed > 55).Select(c => c);

            foreach (var car in fastCars)
            {
                Console.WriteLine("{0} is going too fast!", car.PetName);
            }
        }
Example #5
0
 static void OfTypeAsFilter()
 {
     ArrayList myStaff = new ArrayList();
     myStaff.AddRange(new object[] {10, 400, 8, false, new Car(), "string data"});
     var myInts = myStaff.OfType<int>();
     foreach (int i in myInts)
         Console.WriteLine("Int value: {0}", i);
 }
        private void FilterTheShitOut()
        {
            ArrayList kitchenSink = new ArrayList();
             kitchenSink.AddRange(new object[]{10, 20, "asdfa", true, false, 345.67, new ObjWithProps()});
             IEnumerable<int> filteredInts = kitchenSink.OfType<int>();

             foreach( int i in filteredInts )
            Console.WriteLine(i);
        }
Example #7
0
        public static int OfTypeAsFilter() {
            var myStuff = new ArrayList();
            myStuff.AddRange(new object[] {15, false, new Car {PetName = "BMW", MaxSpeed = 260}, "str1", 559.3, 255, 42.0f, true, new Car("Toyouta", 230, 50) });

            var myInts = myStuff.OfType<int>();
            var myCars = myStuff.OfType<Car>();
            var myDoubles = myStuff.OfType<double>();
            var myFloats = myStuff.OfType<float>();
            var myBools = myStuff.OfType<bool>();

            myInts.PrintEnumerable();
            myCars.PrintEnumerable();
            myDoubles.PrintEnumerable();
            myBools.PrintEnumerable();
            myFloats.PrintEnumerable();


            return 0;
        }
        public void OfTypeMethodTest()
        {
            ArrayList fruits = new System.Collections.ArrayList();
            fruits.Add("Mango");
            fruits.Add("Orange");
            fruits.Add("Apple");
            fruits.Add(3.0);
            fruits.Add("Banana");

            // type을 지정해 그 type으로 cast 할 수 있는 element만 열거
            IEnumerable<string> query = fruits.OfType<string>();
            Assert.AreEqual(4, query.Count(), "3.0은 제외한 나머지 4개");
        }
Example #9
0
        static void Main()
        {
            ArrayList list = new ArrayList { "First", "Second", "Third"};
            var strings = list.Cast<string>();
            foreach (string item in strings)
            {
                Console.WriteLine(item);
            }

            list = new ArrayList { 1, "not an int", 2, 3};
            var ints = list.OfType<int>();
            foreach (int item in ints)
            {
                Console.WriteLine(item);
            }
        }
Example #10
0
        public static void Test()
        {
            ArrayList list = new ArrayList();
            list.Add("apple");
            list.Add("orange");
            list.Add(1);
            list.Add(2);

            var rst = list.OfType<string>();
            foreach (var item in rst)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
Example #11
0
        public static int QueryOverArrayList() {
            var myCars = new ArrayList() {
                 new Car{ PetName = "Henry", Color = "Silver", MaxSpeed = 100, Make = "BMW"},
                 new Car{ PetName = "Daisy", Color = "Tan", MaxSpeed = 90, Make = "BMW"},
                 new Car{ PetName = "Mary", Color = "Black", MaxSpeed = 55, Make = "VW"},
                 new Car{ PetName = "Clunker", Color = "Rust", MaxSpeed = 5, Make = "Yugo"},
                 new Car{ PetName = "Melvin", Color = "White", MaxSpeed = 43, Make = "Ford"}
                 };

            var myCarsEnum = myCars.OfType<Car>();
            var fastCars = from c in myCarsEnum where c.MaxSpeed > 55 select c;

            fastCars.PrintEnumerable();


            return 0;
        }
Example #12
0
        static void LINQOverArrayList()
        {
            Console.WriteLine("***** LINQ at ArrayList *****\n");
            ArrayList myCars = new ArrayList()
                               {
                                       new Car{PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"},
                                       new Car{PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
                                       new Car{PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"},
                                       new Car{PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"},
                                       new Car{PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"}

                               };
            var myCarsEnum = myCars.OfType<Car>();
            var fastCars = from c in myCarsEnum where c.Speed > 55 select c;
            foreach (var car in fastCars)
                Console.WriteLine("{0} is going too fast!", car.PetName);
        }
Example #13
0
 private void Frm_Main_Load(object sender, EventArgs e)
 {
     ArrayList arrList = new ArrayList(); //创建动态数组
     arrList.Add(1);//添加动态数组元素
     arrList.Add(2);
     arrList.Add("A");
     arrList.Add(3);
     arrList.Add("b");
     //使用LINQ筛选动态数组中是string类型的元素
     var query = from item in arrList.OfType<string>()
                 select item;
     label1.Text = "是字符串类型的有:";//显示string类型的元素
     foreach (var item in query)
     {
         label1.Text += item + " , ";
     }
 }
        private object PopulateStockOutList(CoralPOS.Models.StockIn selectedStockIn)
        {
            var details = new ArrayList(StockOutDetails);
            foreach (StockInDetail inDetail in selectedStockIn.StockInDetails)
            {
                Product product = inDetail.Product;
                if (!ProductInStockOutList(details, product))
                {
                    // create new stockout detail for that product
                    StockOutDetail newDetail = DataErrorInfoFactory.Create<StockOutDetail>();
                    newDetail.Product = inDetail.Product;
                    newDetail.ProductMaster = inDetail.ProductMaster;
                    newDetail.CreateDate = DateTime.Now;
                    newDetail.UpdateDate = DateTime.Now;
                    newDetail.CreateId = "admin";
                    newDetail.UpdateId = "admin";
                    newDetail.Quantity = inDetail.Quantity;
                    newDetail.StockQuantity = inDetail.Stock.Quantity;
                    newDetail.GoodQuantity = inDetail.Quantity;
                    details.Add(newDetail);
                }
                else
                {
                    StockOutDetail result = (from sod in details.OfType<StockOutDetail>()
                                             where sod.Product.ProductId.Equals(product.ProductId)
                                             select sod).FirstOrDefault();
                    result.Quantity += inDetail.Quantity;
                    result.GoodQuantity += inDetail.Quantity;
                }
            }

            StockOutDetails = details;
            return null;
        }
        private object LoadBarcode()
        {
            if (ObjectUtility.LengthEqual(Barcode, 12))
            {
                ArrayList details = new ArrayList(StockOutDetails);

                StockOutDetail result = (from sod in details.OfType<StockOutDetail>()
                                         where sod.Product.ProductId.Equals(Barcode)
                                         select sod).FirstOrDefault();
                if (result != null) // if exist in list
                {
                    result.Quantity += 1;
                }
                else
                {
                    // get information from database
                    MainStock stock = MainStockLogic.FindByProductId(Barcode);
                    // create new stockout detail for that product
                    StockOutDetail newDetail = DataErrorInfoFactory.Create<StockOutDetail>();
                    newDetail.Product = stock.Product;
                    newDetail.ProductMaster = stock.ProductMaster;
                    newDetail.CreateDate = DateTime.Now;
                    newDetail.UpdateDate = DateTime.Now;
                    newDetail.CreateId = "admin";
                    newDetail.UpdateId = "admin";
                    newDetail.Quantity = 1;
                    newDetail.StockQuantity = stock.Quantity;

                    details.Add(newDetail);
                }

                StockOutDetails = details;

            }
            return null;
        }
        public void CreateByFile()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*.txt | Text Files";
            openFileDialog.CheckFileExists = true;
            openFileDialog.ShowDialog();
            // if has file to open
            if (!string.IsNullOrEmpty(openFileDialog.FileName))
            {
                IList<string> errorList;
                IDictionary<string, long> productList = ObjectUtility.ReadProductList(openFileDialog.FileName, out errorList);

                // add to stockOut list
                ArrayList details = new ArrayList(StockOutDetails);
                foreach (KeyValuePair<string, long> keyValuePair in productList)
                {
                    StockOutDetail result = (from sod in details.OfType<StockOutDetail>()
                                             where sod.Product.ProductId.Equals(keyValuePair.Key)
                                             select sod).FirstOrDefault();
                    if (result != null) // if exist in list
                    {
                        result.Quantity += keyValuePair.Value;
                    }
                    else
                    {
                        // get information from database
                        MainStock stock = MainStockLogic.FindByProductId(keyValuePair.Key);
                        errorList.Add(keyValuePair.Key);
                        // create new stockout detail for that product
                        StockOutDetail newDetail = DataErrorInfoFactory.Create<StockOutDetail>();
                        newDetail.Product = stock.Product;
                        newDetail.ProductMaster = stock.ProductMaster;
                        newDetail.CreateDate = DateTime.Now;
                        newDetail.UpdateDate = DateTime.Now;
                        newDetail.CreateId = "admin";
                        newDetail.UpdateId = "admin";
                        newDetail.Quantity = keyValuePair.Value;
                        newDetail.StockQuantity = stock.Quantity;
                        newDetail.GoodQuantity = keyValuePair.Value;
                        details.Add(newDetail);
                    }
                }
                StockOutDetails = details;
            }
        }
        public void CodeGenerationStartedTest()
        {
            // Arrange
            WebPageRazorHost host = new WebPageRazorHost("~/Foo/Baz.cshtml", @"C:\Foo\Baz.cshtml");
            RazorBuildProvider provider = CreateBuildProvider("foo @bar baz");
            provider.Host = host;

            // Expected original base dependencies
            var baseDependencies = new ArrayList();
            baseDependencies.Add("/Samples/Foo/Baz.cshtml");

            // Expected list of dependencies after GenerateCode is called
            var dependencies = new ArrayList();
            dependencies.Add(baseDependencies[0]);
            dependencies.Add("/Samples/Foo/Foo.cshtml");

            // Set up the event handler
            provider.CodeGenerationStartedInternal += (sender, e) =>
            {
                var bp = sender as RazorBuildProvider;
                bp.AddVirtualPathDependency("/Samples/Foo/Foo.cshtml");
            };

            // Set up the base dependency
            MockAssemblyBuilder builder = new MockAssemblyBuilder();
            typeof(BuildProvider).GetField("_virtualPath", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(provider, CreateVirtualPath("/Samples/Foo/Baz.cshtml"));

            // Test that VirtualPathDependencies returns the original dependency before GenerateCode is called
            Assert.True(baseDependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));

            // Act
            provider.GenerateCodeCore(builder);

            // Assert
            Assert.NotNull(provider.AssemblyBuilderInternal);
            Assert.Equal(builder, provider.AssemblyBuilderInternal);
            Assert.True(dependencies.OfType<string>().SequenceEqual(provider.VirtualPathDependencies.OfType<string>()));
            Assert.Equal("/Samples/Foo/Baz.cshtml", provider.VirtualPath);
        }
Example #18
0
		public void of_type()
		{
			var fixtures = new ArrayList();
			fixtures.Add(new RavenJObject());
			fixtures.AddRange(CreateSequentialFixtures(3));
			fixtures.Add(new RavenJObject());

			var sut = CreateDynamicList(fixtures);

			Assert.Equal(fixtures.OfType<Fixture>().ToList(), sut.OfType<Fixture>().ToList());
			Assert.Equal(fixtures.OfType<RavenJObject>().ToList().Count, sut.OfType<RavenJObject>().ToList().Count);
		}
        /// <summary>
        /// Inserts the barcode to list.
        /// </summary>
        /// <param name="details">The details.</param>
        /// <param name="productId">The product id.</param>
        /// <param name="quantity">The quantity.</param>
        private void InsertBarcodeToList(ArrayList details, string productId, long quantity)
        {
            if (quantity == 0) return;

            DepartmentStockTempValid result = (from sod in details.OfType<DepartmentStockTempValidDTO>()
                                               from stv in sod.DepartmentStockTempValids
                                               where stv.Product.ProductId.Equals(productId)
                                               select stv).FirstOrDefault();
            if (result != null) // if exist in list
            {
                result.GoodQuantity += quantity;
            }
            else
            {

                // get information from database
                DepartmentStockTempValid tempValid = DepartmentStockTempValidLogic.CreateFromProductId(productId, SelectedDepartment.DepartmentId);
                if (tempValid == null)
                {
                    //throw new InvalidDataException("Can not found product in database !");
                    //MessageBox.Show("Can not found product in database !");
                    return;
                }
                tempValid.GoodQuantity = quantity;

                DepartmentStockTempValidDTO dto = (from sod in details.OfType<DepartmentStockTempValidDTO>()
                                                   where
                                                           sod.ProductMaster.ProductMasterId == tempValid.ProductMaster.ProductMasterId
                                                        && sod.ProductColor.ColorId          == tempValid.Product.ProductColor.ColorId
                                                        && sod.ProductSize.SizeId            == tempValid.Product.ProductSize.SizeId
                                                   select sod).FirstOrDefault();
                if (dto != null)
                {
                    dto.DepartmentStockTempValids.Add(tempValid);
                }
                else
                {
                    details.Add(DepartmentStockTempValidDTO.CreateFrom(tempValid));
                }
            }
        }
Example #20
0
        public static void PrintOftype()
        {
            var arr = new object[5];
            arr[0] = new StringBuilder();
            arr[1] = "string";
            arr[2] = "integer";
            arr[3] = new int[1];
            arr[4] = new double[3];

            var arrayList = new ArrayList {new StringBuilder(), "string1", "string2", new int[1], 1, 2, 3.1};

            var ofTypeArr = arrayList.OfType<double>();
            foreach (var i in ofTypeArr)
            {
                Console.WriteLine("{0:0.0}",i);
            }
        }
Example #21
0
        static void OfTypeAsFilter()
        {
            // Extract the ints from the ArrayList.
            ArrayList myStuff = new ArrayList();
            myStuff.AddRange(new object[] { 10, 400, 8, false, new Car(), "string data" });
            IEnumerable<int> myInts = myStuff.OfType<int>();

            // Prints out 10, 400, and 8.
            foreach (int i in myInts)
            {
                Console.WriteLine("Int value: {0}", i);
            }
        }
        /*public static IEnumerable<T> OfType<T>(
         *  this IEnumerable source);
         *  */
        void OfTypeOperator()
        {
            ArrayList employees = Employee.GetEmployeesArrayList();
            EmployeeOptionEntry[] empOptions = EmployeeOptionEntry.GetEmployeeOptionEntries();

            ArrayList al = new ArrayList();
            al.Add(employees[0]);
            al.Add(employees[1]);
            al.Add(empOptions[0]);
            al.Add(empOptions[1]);
            al.Add(employees[3]);
            al.Add(empOptions[3]);

            var items = al.Cast<Employee>();

            Console.WriteLine("Attemting to use the Cast operator ...");
            try
            {
                foreach (Employee item in items)
                {
                    Console.WriteLine("{0} {1} {2}", item.id, item.firstName, item.lastName);
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("{0} {1}", ex.Message, System.Environment.NewLine);
            }

            Console.WriteLine("Attempting to use the OfType operator...");
            var items2 = al.OfType<Employee>();
            foreach (Employee item in items2)
            {
                Console.WriteLine("{0} {1} {2}", item.id, item.firstName, item.lastName);
            }
        }
 private IList SortType(ArrayList findAll)
 {
     var result = from det in findAll.OfType<ProductType>()
                  orderby det.TypeName ascending
                  select det;
     return result.ToList();
 }
			public static bool SAID(TriggerObject trigObject, ArrayList testWords)
			{
				return testWords != null && testWords.Count > 0 && testWords.OfType<string>().Any(test => SAID(trigObject, test));
			}
        private object LoadBarcode()
        {
            if (ObjectUtility.LengthEqual(Barcode, 12))
            {
                IEnumerable enumerable = DepartmentPurchaseOrderLogic.ProcessBarcode(Barcode);
                IEnumerator enumerator = enumerable.GetEnumerator();
                enumerator.MoveNext();
                Product product = (Product)enumerator.Current;

                DepartmentPurchaseOrderDetail detail = new DepartmentPurchaseOrderDetail
                {
                    DelFlg = 0,
                    CreateDate = DateTime.Now,
                    CreateId = "admin",
                    UpdateDate = DateTime.Now,
                    UpdateId = "admin",
                    ExclusiveKey = 1,
                    Product = product,
                    ProductMaster = product.ProductMaster,
                    DepartmentPurchaseOrder = DepartmentPurchaseOrder,
                    Quantity = 1
                };

                if (product.AdhocCase > 0)
                    detail.AdhocCase = product.AdhocCase;
                long maxId = 0;
                if (PurchaseOrderDetails.Count > 0)
                {
                     maxId = PurchaseOrderDetails.OfType<DepartmentPurchaseOrderDetail>().Max(
                        det => det.DepartmentPurchaseOrderDetailPK.PurchaseOrderDetailId);
                }
                DepartmentPurchaseOrderDetailPK pk = new DepartmentPurchaseOrderDetailPK
                {
                    DepartmentId = 1,
                    PurchaseOrderDetailId = ++maxId,
                    PurchaseOrderId = DepartmentPurchaseOrder.DepartmentPurchaseOrderPK.PurchaseOrderId
                };
                detail.DepartmentPurchaseOrderDetailPK = pk;
                var detailList = new ArrayList(PurchaseOrderDetails);
                DepartmentPurchaseOrderDetail current =
                    detailList.OfType<DepartmentPurchaseOrderDetail>().FirstOrDefault(
                        det => det.Product.ProductId.Equals(detail.Product.ProductId));

                if (current != null)
                {
                    current.Quantity += 1;
                }
                else
                {
                    enumerator.MoveNext();
                    detail.Price = ((MainPrice)enumerator.Current).Price;
                    detailList.Add(detail);
                }

                PurchaseOrderDetails = detailList;
                CalculatePrice();
                Barcode = "";

            }
            return null;
        }
        private static TransformResultInfo DoTransform(XElement template)
        {
            Log.LogThis("Starting invoice transform", eloglevel.info);
            Log.LogThis(string.Format("Using invoice template: Id: {0} Name: {1}", template.Attribute("Id").Value, template.Attribute("Name").Value), eloglevel.info);
            Log.LogThis(string.Format("Loading original invoice file(s) from: {0}", template.Attribute("SourceFolder").Value), eloglevel.info);

            List<string> filelist = Directory.GetFiles(template.Attribute("SourceFolder").Value).OfType<string>().ToList();
            Log.LogThis(string.Format("Invocie files found: {0}", string.Join(",", filelist.Select(Path.GetFileName).ToArray())), eloglevel.info);

            _templateTransformFields = template.Descendants("TemplateTransform").FirstOrDefault();
            _selectedTemplate = template;
            _selectedTemplate.Element("InvoiceNumbersToUpdate").RemoveAll();

            var eachesConversionElement = _selectedTemplate.Element("EachesConversion");

            _useEachesConversion = (eachesConversionElement != null && eachesConversionElement.Attribute("enabled") != null && eachesConversionElement.Attribute("enabled").Value == "1");
            _eachesConverionTag = _useEachesConversion && eachesConversionElement.Attribute("tag") != null ? eachesConversionElement.Attribute("tag").Value : "";

            var transformResultInfo = new TransformResultInfo();
            var newSplitLine = new ArrayList();

            var fileInvoices = new Dictionary<string, List<string[]>>();

            foreach (string file in filelist)
            {
                Log.LogThis(string.Format("Processing file: {0}", file), eloglevel.info);
                fileInvoices.Add(file, new List<string[]>());

                transformResultInfo.NumberOfFilesProcessed += 1;

                int newFieldPos = 0;
                XElement invoiceNoTemplateField = null;
                XElement invoiceDateTemplateField = null;

                var sr = new StreamReader(file);

                if (_selectedTemplate.Attribute("HasHeaderRecord").Value == "1")
                {
                    sr.ReadLine(); //advance past the header line
                }

                while (!sr.EndOfStream)
                {
                    var csvParser = new CsvParser(_selectedTemplate.Attribute("Delimiter").Value[0], '\0');

                    var splitOriginalLine = (string[])csvParser.CSVParser(sr.ReadLine()).ToArray(typeof(string));

                    if (splitOriginalLine.Count() == 0)
                        continue;

                    newSplitLine.Clear();

                    if (_selectedTemplate.Attribute("HasMasterRecord").Value == "1" && IsMasterRow(splitOriginalLine))
                    {
                        invoiceNoTemplateField = _selectedTemplate.Descendants("MasterRow").Descendants("Field").FirstOrDefault(x => x.Attribute("FieldNameId").Value == "1");
                        _invoiceNumber = splitOriginalLine[int.Parse(invoiceNoTemplateField.Descendants("Delimited").First().Attribute("Position").Value)];

                        invoiceDateTemplateField = _selectedTemplate.Descendants("MasterRow").Descendants("Field").FirstOrDefault(x => x.Attribute("FieldNameId").Value == "2");
                        _invoiceDate = splitOriginalLine[int.Parse(invoiceDateTemplateField.Descendants("Delimited").First().Attribute("Position").Value)];
                    }
                    else if (IsDetailRow(splitOriginalLine))
                    {
                        if (_selectedTemplate.Attribute("HasMasterRecord").Value == "1")
                        {
                            newSplitLine.Add(_invoiceNumber);
                            SetNewFieldPosition(invoiceNoTemplateField, ref newFieldPos);

                            newSplitLine.Add(_invoiceDate);
                            SetNewFieldPosition(invoiceDateTemplateField, ref newFieldPos);
                        }

                        foreach (XElement templateField in _selectedTemplate.Element("DetailFields").Descendants("Field"))
                        {
                            string fieldValue = splitOriginalLine[int.Parse(templateField.Descendants("Delimited").First().Attribute("Position").Value)];

                            if (templateField.Attribute("DirectiveId") != null &&
                                !string.IsNullOrEmpty(templateField.Attribute("DirectiveId").Value))
                            {
                                Log.LogThis("Alternative processing directive found for fieldNameId " + templateField.Attribute("FieldNameId").Value + ", directiveId " + templateField.Attribute("DirectiveId").Value, eloglevel.info);

                                var fieldDirective = _selectedTemplate.Element("Directives").Descendants("Directive").FirstOrDefault(directive => directive.Attribute("Id").Value == templateField.Attribute("DirectiveId").Value);
                                var sourceFieldConditionValue = splitOriginalLine[int.Parse(fieldDirective.Element("Condition").Attribute("ConditionFieldPosition").Value)];

                                Log.LogThis("DirectiveId " + fieldDirective.Attribute("Id").Value + ": Name: " + fieldDirective.Attribute("Name").Value, eloglevel.info);

                                decimal result = decimal.Parse(fieldValue);

                                if (sourceFieldConditionValue == fieldDirective.Element("Condition").Attribute("ConditionValue").Value)
                                {
                                    var operand1 = decimal.Parse(splitOriginalLine[int.Parse(fieldDirective.Element("Calculation").Element("Operand1").Attribute("sourceFieldPosition").Value)]);
                                    var operand2 = decimal.Parse(splitOriginalLine[int.Parse(fieldDirective.Element("Calculation").Element("Operand2").Attribute("sourceFieldPosition").Value)]);
                                    var op = fieldDirective.Element("Calculation").Element("Operator").Attribute("OpType").Value;

                                    switch (op)
                                    {
                                        case "division":
                                            result = operand1 / (operand2 == 0 ? 1 : operand2);
                                            Log.LogThis("Performing directive: " + operand1 + " / " + (operand2 == 0 ? 1 : operand2) + " = " + result, eloglevel.info);
                                            break;
                                        case "multiply":
                                            result = operand1 * operand2;
                                            break;
                                        case "add":
                                            result = operand1 + operand2;
                                            break;
                                        case "minus":
                                            result = operand1 - operand2;
                                            break;
                                        default:
                                            break;
                                    }

                                    fieldValue = result.ToString("F4");
                                }
                            }

                            newSplitLine.Add(fieldValue);
                            SetNewFieldPosition(templateField, ref newFieldPos);
                        }

                        //if (!IgnoreNegativeAmountLines(new[] { "UnitCost", "TotalCost" }, newSplitLine))
                            fileInvoices[file].Add(newSplitLine.OfType<string>().ToArray()); //build a list of all the detail lines
                    }
                    else if (IsSummaryRow(splitOriginalLine))
                    {
                        //ignore summary lines
                    }
                }
                sr.Close();

                transformResultInfo.NumberOfInvoiceLinesProcessed += fileInvoices[file].Count;
                ArchiveProcessedInvoiceFile(file);
            }

            var allDetailLines = fileInvoices.Values.SelectMany(l => l).ToList();
            if (allDetailLines.Count > 0)
            {
                foreach (var inv in allDetailLines.Select(invLine => invLine[0]).Distinct().ToList())
                    _selectedTemplate.Element("InvoiceNumbersToUpdate").Add(new XElement("InvoiceNumber", inv));

                CreateFixedLengthFieldsAndTransformDetials(fileInvoices);

                SaveTransformedInvoiceFile(fileInvoices);
            }

            return transformResultInfo;
        }
Example #27
0
        public void Execute()
        {
            var persons = new List<Person>
            {
                new Person {Id = 1, Name = "gsf_zero1"},
                new Person {Id = 2, Name = "gsf_zero2"},
                new Customer {Id = 3, Name = "gsf_zero3", Orders = Enumerable.Empty<Order>()},
                new Customer
                {
                    Id = 4,
                    Name = "gsf_zero4",
                    Orders = new List<Order>
                    {
                        new Order {Id = 1, Quantity = 10},
                        new Order {Id = 2, Quantity = 2}
                    }
                },
                new Person {Id = 5, Name = "gsf_zero5"}
            };

            //
            // OfTypeメソッドを利用することにより、特定の型のみのシーケンスに変換することができる。
            // 例えば、リストの中に基底クラスであるPersonクラスと派生クラスであるCustomerクラスの
            // オブジェクトが混在している場合、OfType<Person>とすると、そのまま。
            // OfType<Customer>とすると、Customerオブジェクトのみのシーケンスに変換される。
            //
            // 尚、OfTypeメソッドは他の変換演算子とは違い、ソースシーケンスのスナップショットを作成しない。
            // つまり、通常のクエリと同じく、OfTypeで取得したシーケンスが列挙される度に評価される。
            // 変換演算子の中で、このような動作を行うのはAsEnumerableとOfTypeとCastである。
            //
            Output.WriteLine("========== OfType<Person>の結果 ==========");
            foreach (var data in persons.OfType<Person>())
            {
                Output.WriteLine(data);
            }

            Output.WriteLine("========== OfType<Customer>の結果 ==========");
            foreach (var data in persons.OfType<Customer>())
            {
                Output.WriteLine(data);
            }

            /*
              IEnumerable<Customer> c = persons.OfType<Customer>();
              persons.Add(new Customer { Id = 99, Name = "gsf_zero3", Orders = Enumerable.Empty<Order>() });

              foreach (var data in c)
              {
                Output.WriteLine(data);
              }
            */

            //
            // 元々GenericではないリストをIEnumerable<T>に変換する場合にも利用出来る.
            //
            var arrayList = new ArrayList();
            arrayList.Add(10);
            arrayList.Add(20);
            arrayList.Add(30);
            arrayList.Add(40);

            Output.WriteLine("========== Genericではないコレクションを変換 ==========");
            var intList = arrayList.OfType<int>();
            foreach (var data in intList)
            {
                Output.WriteLine(data);
            }
        }
Example #28
0
        private static void SimpleQueries2() {
            var cars = new List<Car> {
                new Car {CarName = "Opel", MaxSpeed = 240},
                new Car {CarName = "BMW", MaxSpeed = 260},
                new Car {CarName = "BMW", MaxSpeed = 220},
                new Car {CarName = "Audi", MaxSpeed = 250}
            };
            Console.WriteLine("*** Whole cars:***");
            cars.PrintCollection();
            Console.WriteLine("*** Fast cars:***");
            GetFastCars(cars).PrintCollection();
            Console.WriteLine("*** Fast BMWs:***");
            GetFastBMWs(cars).PrintCollection();

            // BUT!!!
            // Non-generic collections (such as ArrayList) are not compatible with IEnumerable interface
            // that is needed for LINQ queries!
            // so we need to transform them!!!
            // that also because such containers can contain any type of data!!!
            var carList = new ArrayList {
                new Car {CarName = "Opel", MaxSpeed = 240},
                new Car {CarName = "BMW", MaxSpeed = 260},
                new Car {CarName = "BMW", MaxSpeed = 220},
                new Car {CarName = "Audi", MaxSpeed = 250},
                // non-Car objects wont appear in casted list
                new object(),
                new Point {X = 2, Y = 3},
                false,
                42
            };

            Console.WriteLine("*** ArrayList collection:***");
            // casting (filtering) to IEnumerable<Car>
            GetFastCars(carList.OfType<Car>()).PrintCollection();
        }
 private IList SortDetail(ArrayList stockInDetails)
 {
     var result = from detail in stockInDetails.OfType<StockInDetail>()
                  orderby detail.Product.ProductMaster.ProductName,
                          detail.Product.ProductMaster.ProductColor.ColorId,
                          detail.Product.ProductMaster.ProductSize.SizeId ascending
                  select detail;
     return result.ToList();
 }
Example #30
0
        static void Main(string[] args)
        {
            var users = EntityMapper.LoadUsers();
            var badges = EntityMapper.LoadBadges();

            #region ToList, ToDictionary, ToArray, ToLookup

            //In LINQ, the results of our queries are always going to be an IEnumerable of some type
            //LINQ operates in a delayed manner, so the following select won't do anything until we interate over it
            IEnumerable<User> result = users.Select(u => u);

            //Certain operations that need to iterate over the entire enumerable can be expensive, so LINQ provides
            //extensions to put the result of a query straight into a collection. This forces the entire result set
            //to be put into a list; all the work is done in the following line, rather than when we iterate over it
            IEnumerable<User> listResult = users.Select(u => u).ToList();

            //Can also put the results of a query into a dictionary by supplying a key; the following gives us a dictionary
            //of UserID to User. Of course, you need to be sure that the item used as a key is a unique value
            Dictionary<int, User> dict = users.Select(u => u).ToDictionary(u => u.Id);

            //A useful overload to ToDictionary takes a keySelector and an elementSelector, which lets us specify what part
            //of the user we want to be the values in the dictionary
            Dictionary<int, string> newDict = users.Select(u => u).ToDictionary(u => u.Id, u => u.DisplayName);

            //Can also cast into an ILookup, a generic interface that can apply to any item that maps a key to a value.
            //Unlike a dictionary, ILookup is mapping directly to the Lookup type, which was introduced in 3.5 and acts
            //similar to a dictionary, except that you can have repeated keys, and can match a single key to multiple values
            ILookup<int, string> ageToName = users.Select(u => u).ToLookup(u => u.Age, u => u.DisplayName);

            //Here we've created an IEnumerable<IGrouping>, of age to user display name
            foreach (IGrouping<int, string> grouping in ageToName)
            {
                Console.WriteLine(grouping.Key);
                foreach (string displayName in grouping)
                    Console.WriteLine(displayName);
            }

            #endregion

            #region GroupBy

            //We can do a similar thing as ToLookup using the grouping operators, with the added bonus that
            //grouping operations benefit from deferred execution, just like the rest of LINQ
            var ageGrouping = users.GroupBy(u => u.Age);

            //This gives us the same result as the ToLookup example above
            foreach (var group in ageGrouping)
            {
                Console.WriteLine(group.Key);
                foreach (var user in group)
                    Console.WriteLine(user);
            }

            //Again, we get a useful overload that lets us specify an elementSelector. Here we're getting back a grouping
            //of age to displayname, instead of age to user type
            var elementSelect = users.GroupBy(u => u.Age, u => u.DisplayName);

            //Another overload takes a resultsSelector, a lambda which takes in the key and the values from the grouping and do something with them
            var resultSelect = users.GroupBy(u => u.Age, u => u.DisplayName, (key, value) => new { Age = key, Count = value.Count() }).OrderBy(u => u.Count);

            //The above projects the grouping into our anonymous type, instead of an IGrouping
            foreach (var group in resultSelect)
                Console.WriteLine(group.Age + " " + group.Count);

            #endregion

            #region Join and GroupJoin

            //Join operator works just like we'd expect, same as it does in SQL. Basically, we call it on a collection
            //and pass in another collection to join to, spec out selector methods for the outer and inner collections,
            //and then pass in a result selector describing what we'd like to get back from the join
            var joinResult = users.Join(badges,
                                        u => u.Id,
                                        b => b.UserId,
                                        (u, b) => new { User = u, Badge = b });

            foreach (var join in joinResult) Console.WriteLine(join.User.DisplayName + " " + join.Badge.Name);

            Console .WriteLine();

            //We are performing an "inner" join, ie, we aren't getting any results back unless both the left and right
            //side have matching values. There are times we might want a "left outer" join - we want a complete list of an entire
            //side, whether it has matches on the right side or not. You'll have to use the groupjoin operator...
            var groupJoin = users
                            .GroupJoin(badges,
                                 u => u.Id,
                                 b => b.UserId,
                                (u, b) => new { User = u, Badges = b.DefaultIfEmpty() })
                            .SelectMany(a => a.Badges.Select(b => new { User = a.User, Badge = b }));

            foreach (var join in groupJoin)
            {
                Console.WriteLine(join.User.DisplayName + " " +
                    (join.Badge == null ? "" : join.Badge.Name));
            }

            Console.WriteLine();

            #endregion

            #region Zip

            //What zip does is let you take two sequences and combine them item by item. Generally the use case for
            //zip is when you have two sequences and you need to perform two different queries on them, and you need
            //to combine those sequences, sort of like a zipper; first item in list1 goes with first item in list2, etc...

            //Result of the following zip operation is just a concatenated string of doubled up user names
            var zipTest = users.Take(10).Zip(users.Take(10), (u1, u2) => u1.DisplayName + " " + u2.DisplayName);

            foreach (var res in zipTest)
                Console.WriteLine(res);

            //Of course that's kind of silly. But imagine if the two different values were coming from two different queries

            Console.WriteLine();

            #endregion

            #region Cast and OfType

            //Cast lets us take a sequence of types and cast them to another type; really useful with old libraries
            //that might use ArrayLists or something

            var list = new ArrayList();
            list.Add(1);
            list.Add(2);
            list.Add(3);

            //We want to perform some filtering across this list, but in order to perform the predicate, we need some types.
            //You can get a strongly typed IEnumerable<int> using cast
            var castList = list.Cast<int>().Where(i => i > 1);

            Console.WriteLine();

            //But you have to be careful with cast - it will throw an exception if all the items in the list are not
            //of the specified type. If you don't know for certain that the list is singly typed, you can use OfType
            var multiList = new ArrayList();
            list.Add(1);
            list.Add(2.3);
            list.Add(3);

            var onlyInts = list.OfType<int>();

            foreach (var num in onlyInts) Console.WriteLine(num);

            #endregion

            #region Histogram Example
            var listOLists = new List<List<string>>() {
                new List<string>{"CATS", "DERP", "SUPERDERP"},
                new List<string>{"WELP", "DERP", "CATS", "CATS"},
                new List<string>{"WELP", "HNNNGGG", "CATS"}
                };

            var histO = listOLists.SelectMany(x => x).GroupBy(s => s);//.ToDictionary(g => g.Key, v => v.Count());

                //.Select(g => new { Key = g.Count(), Word = g.Key });

            foreach (var group in histO)
            {
                Console.WriteLine(group.Key);
                foreach (var Word in group)
                    Console.WriteLine("\t" + Word);
            }

            //(l, s) => l.Count(x => x == s));
            #endregion

            Console.ReadLine();
        }