Beispiel #1
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (File.Exists(filename))
     {
         SelectFirstThree obj  = new SelectFirstThree();
         List <string>    list = File.ReadAllLines(filename).ToList();
         //findfirst3 是委派函式 委派找到檔案開頭為695 525的檔案
         MyPredicate find   = findfirst3;
         var         result = obj.DoWhere(list, find); //委派的list傳入 find委派函式
         string      st_date;
         string      TickNumber;
         DateTime    Flyingday;
         DateTime    Birthday;
         foreach (var item in result)
         {
             st_date    = item.Substring(0, 13);
             TickNumber = st_date;
             st_date    = item.Substring(13, 8);
             Flyingday  = DateTime.ParseExact(st_date, "yyyyMMdd", null, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
             st_date    = item.Substring(21, 8);
             Birthday   = DateTime.ParseExact(st_date, "yyyyMMdd", null, System.Globalization.DateTimeStyles.AllowWhiteSpaces);
             InsertIntoDatabase(TickNumber, Flyingday, Birthday);
         }
     }
     else
     {
         MessageBox.Show("找不到檔案");
     }
 }
        public Task Test_Serialize_Predicate_Class()
        {
            IMyPredicate pred = new MyPredicate(_staticFilterValue2);

            // Works OK
            TestSerializePredicate("Predicate Class Instance", pred.FilterFunc);

            return(Task.CompletedTask);
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            MyPredicate pr0 = isPos;

            //pr1 takes an int as a paerameter and returns bool
            Predicate <int> pr1 = isPos;

            Console.WriteLine(pr0(7));
            Console.WriteLine(pr1(7));
        }
Beispiel #4
0
 /// <summary>
 /// Перевірка чи відповідає хоч один елемент списку истиності певному твердженню
 /// </summary>
 /// <param name="condition">Предикат</param>
 /// <returns></returns>
 public bool Exist(MyPredicate <T> condition)
 {
     for (int i = 0; i < array.Length; i++)
     {
         if (condition.Invoke(array[i]))
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #5
0
 //  rather than re-writing the same code (almost), pass-in a "condition method"
 //  since we cannot pass a method to a method directly, we do that using
 //  a delegate object. we can pass a delegate object to a method, as a
 //  parameter using the type of condition method we want should have the signature
 //  of MyPredicate
 static int Find(MyPredicate predicate)  //  need to associate 'predicate' with a method in order to invoke that method
 {
     foreach (int x in array)
     {
         if (predicate(x))
         {
             return(x);
         }
     }
     return(0);
 }
Beispiel #6
0
        static uint MyCount(int[] arr, MyPredicate predic)
        {
            uint count = 0;

            foreach (var item in arr)
            {
                if (predic(item))
                {
                    ++count;
                }
            }
            return(count);
        }
Beispiel #7
0
            public static IList <T> Filter <T>(IList <T> source, MyPredicate <T> predicate)
            {
                List <T> ret = new List <T>();

                foreach (T item in source)
                {
                    if (predicate(item))
                    {
                        ret.Add(item);
                    }
                }
                return(ret);
            }
        public static int CountIf <T>(T[] a, MyPredicate <T> p)
        {
            int count = 0;

            foreach (T i in a)
            {
                if (p(i))
                {
                    ++count;
                }
            }
            return(count);
        }
Beispiel #9
0
        public List <string> DoWhere(List <string> source, MyPredicate predicate)
        {
            List <string> result = new List <string>();

            foreach (var item in source)
            {
                if (predicate.Invoke(item))
                {
                    result.Add(item);
                }
            }
            return(result);
        }
Beispiel #10
0
            static public List <T> MyFindAll <T>(T[] arr, MyPredicate <T> predic)
            {
                List <T> elems = new List <T>();

                foreach (var item in arr)
                {
                    if (predic(item))
                    {
                        elems.Add(item);
                    }
                }
                return(elems);
            }
Beispiel #11
0
        static void Main(string[] args)
        {
            PreloadArray();
            Display(array);

            //  find the first value that is positive
            MyPredicate predicate = IsPositive;
            int         firstPosX = Find(predicate); //  compiler creates a delegate to be passed to the Find() method

            Console.WriteLine($"\n\nFirst positive value: { firstPosX }.");

            //  find the first value that is negative
            predicate = IsNegative;
            int firstNegX = Find(predicate);

            Console.WriteLine($"\n\nFirst negative value: { firstNegX }.");

            //  find the first value that is negative and odd
            predicate = IsNegativeOdd;
            int firstNegOddX = Find(predicate);

            Console.WriteLine($"\n\nFirst negative odd value: { firstNegOddX }.");

            //  find the first value that is positive and even
            predicate = IsPositiveEven;
            int firstPosEvenX = Find(predicate);

            Console.WriteLine($"\n\nFirst positive even value: { firstPosEvenX }.");

            //  another way to do this: pass a delegate referencing a lambda expression
            MyPredicate predicate2       = x => (x) > 0 && x % 2 != 0; //  boolean expression for 'positive' 'odd'
            int         firstPositiveOdd = Find(predicate2);

            Console.WriteLine($"\n\nFirst positive odd value (Lambda-style): { firstPositiveOdd }.");

            //  Create an example using a Delegate that takes two int parameters and returns bool
            //  then wire-up the Delegate to a method that collects all matching instances of x
            //  return the count of matches
            MyPredicate2 mp2     = AreEqual;
            List <int>   matches = MyFindAll(mp2);

            Console.WriteLine($"\n\nNumber of matching items found: { matches.Count }.");


            Console.WriteLine("\n\nPress <Enter> to exit. . .");
            Console.ReadLine();
        }
Beispiel #12
0
        public static int CountElements(this int[] arr, MyPredicate predicate)
        {
            int counter = 0;

            foreach (var item in arr)
            {
                if (predicate(item))
                {
                    counter++;
                }
                else
                {
                    Console.WriteLine("false number");
                }
            }
            return(counter);
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            List <string> source = new List <string> {
                "Bill", "John", "David", "Tom", "David"
            };
            MyPredicate predicate = SearchDavid;
            MyClass     myClass   = new MyClass();

            Console.Write("Ender :");
            string s      = Console.ReadLine();
            var    result = myClass.DoWhere(source, predicate, s);

            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
Beispiel #14
0
        public Form1()
        {
            InitializeComponent();
            //1: Create a delegate object to a named method
            //d1 = new MyPredicate(IsEvenPositive);
            //Or use a short-cut syntax
            d1 = IsEvenPositive;
            //2: Create a delegate to an anonymous method
            d2 = delegate(int x)
            {
                return(x > 0 && x % 2 == 0);
            };
            //3: Create a delegate to a lambda expression
            d3 = x => x > 0 && x % 2 == 0;

            d4 = (x, y) => x > 0 && x % 2 == 1 && y >= Math.Pow(x, 2);

            d5 = (a, b) => (a.Average() + b.Average() / 2);
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            var words = new List <string>()
            {
                "1", "12", "123", "1234", "12345", "12346", "1234567"
            };

            Console.Write("Maximum length of string to include? ");
            int userMaxLength = int.Parse(Console.ReadLine());                     // userMaxLength scope is in Main
            MyPredicate <string> predicate  = item => item.Length < userMaxLength; // we create an anonymous method that uses a variable decalred outside of itself
            IList <string>       shortWords = ListUtil.Filter(words, predicate);   // this method is passed to another method

            ListUtil.Dump(shortWords);                                             // and userMaxLength int is still available

            //Console.WriteLine("Changing the value of the scoped variable within the predicate:");
            //userMaxLength = 0;
            //MyPredicate<string> predicate2 = item => { userMaxLength++; return item.Length <= userMaxLength; };
            //IList<string> shortWords2 = ListUtil.Filter(words, predicate2);
            //ListUtil.Dump(shortWords2);
        }
Beispiel #16
0
        static void Main(string[] args)
        {
            // 建立來源資料
            List <string> source = new List <string> {
                "Bill", "John", "David", "Tom", "David"
            };


            MyCalss obj = new MyCalss();
            // 傳統的具名寫法
            MyPredicate predicate = SearchDavid;
            var         result    = obj.DoWhere(source, SearchDavid);

            // 以上兩行行加上 SearchDavid 方法可以用匿名委派的寫法
            // 請看 DelegateSample003

            foreach (var item in result)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();
        }
Beispiel #17
0
    string MyPreParser(string myCondition)
    {
        if (myCondition == "")
        {
            print("MyPreParser: Ошибка! Для подготовки логического условия передана пустая строка.");
            return("");
        }

        // Массив структур для отдельных условий
        List <MyPredicate> myPredicates = new List <MyPredicate>();

        // Соберем выделенные в [...] единичные условия в массив List
        int myStart = 0;              // с какого символа начинать поиск

        for (int i = 0; i < 100; i++) // на всякий случай число возможных предикатов ограничено
        {
            // Ищем [
            int myOpenBracket = myCondition.IndexOf("[", myStart);
            if (myOpenBracket == -1) // Открывающая скобка не найдена
            {
                break;               // Больше нет единичных условий
            }
            // Ищем ]
            int myCloseBracket = myCondition.IndexOf("]", myStart);
            if (myCloseBracket == -1) // Закрывающая скобка не найдена
            {
                print("MyPreParser: Ошибка! При подготовке логического условия обнаружена незакрытая квадратная скобка.");
                return("");
            }

            // Вырежем единичное условие и заполним структуру
            MyPredicate myPredicate = new MyPredicate();
            myPredicate.PrString = myCondition.Substring(myOpenBracket + 1, myCloseBracket - myOpenBracket - 1);
            myPredicate.OpenBr   = myOpenBracket;
            myPredicate.CloseBr  = myCloseBracket;

            //print("myStart = " + myStart + " myOpenBracket = " + myOpenBracket + " myCloseBracket = " + myCloseBracket + " mySubStr = " + myPredicate.PrString);

            // Добавим структуру в массив
            myPredicates.Add(myPredicate);
            // Новый старт для поиска
            myStart = myCloseBracket + 1;
            if (myStart >= myCondition.Length)
            {
                break; // дошли до конца строки
            }
        }

        // Cтрока для формирования окончательного логического выражения
        StringBuilder myCond = new StringBuilder();


        // Обработаем каждый предикат
        for (int i = 0; i < myPredicates.Count; i++)
        {
            print(myPredicates[i]);
            string[] mySubStr  = myPredicates[i].PrString.Split(new char[] { '.', '=' });
            string   myPath    = mySubStr[0];
            string   propName  = mySubStr[1];
            string   propValue = mySubStr[2];

            // Получить Control:
            print("myPath = " + myPath);
            Control ctrl = _worldController.SourceControls[myPath];
            bool    result;
            // Получить логическое значение предиката
            if (ctrl != null)
            {
                result = ctrl.GetState(propName, propValue);
            }
            else
            {
                print("MyPreParser: Не удается получить Control по пути: " + myPath);
                result = false;
            }

            // Собрать строку, заменяя в ней условия [...] на их логические значения
            if (i == 0) // могут быть символы до первой открывающейся скобки
            {
                myCond.Append(myCondition.Substring(0, myPredicates[i].OpenBr));
            }
            myCond.Append(result);
            if (i < myPredicates.Count - 1) // это еще не последний предикат
            {
                myCond.Append(myCondition.Substring(myPredicates[i].CloseBr + 1, myPredicates[i + 1].OpenBr - myPredicates[i].CloseBr - 1));
            }
            else // а вот это уже последний
            {
                myCond.Append(myCondition.Substring(myPredicates[i].CloseBr + 1, myCondition.Length - myPredicates[i].CloseBr - 1));
            }
        }
        print("MyPreParser return  " + myCond.ToString());
        return(myCond.ToString());
    }