|
@@ -1,109 +1,406 @@
|
|
|
-# Конспект лекции "Регулярные выражения"
|
|
|
-## Регулярки в C#
|
|
|
+# LINQ
|
|
|
+# ʕ•͡-•ʔ
|
|
|
+## Основы LINQ
|
|
|
+### Выберем из массива строки, начинающиеся на определенную букву и отсортируем полученный список:
|
|
|
```
|
|
|
-string s = "Бык тупогуб, тупогубенький бычок, у быка губа бела была тупа";
|
|
|
-Regex regex = new Regex(@"туп(\w*)");
|
|
|
-MatchCollection matches = regex.Matches(s);
|
|
|
-if (matches.Count > 0)
|
|
|
+string[] students = {"Женя", "Моисей", "Влада", "Амир", "Маша", "Катя"};
|
|
|
+
|
|
|
+var selectedStudents = new List<string>();
|
|
|
+
|
|
|
+foreach(string s in students)
|
|
|
{
|
|
|
- foreach (Match match in matches)
|
|
|
- Console.WriteLine(match.Value);
|
|
|
+ if (s.ToUpper().StartsWith("М"))
|
|
|
+ selectedStudents.Add(s);
|
|
|
}
|
|
|
-else
|
|
|
+
|
|
|
+selectedStudents.Sort();
|
|
|
+
|
|
|
+foreach (string s in selectedStudents)
|
|
|
+ Console.WriteLine(s);
|
|
|
+```
|
|
|
+```
|
|
|
+Маша
|
|
|
+Моисей
|
|
|
+```
|
|
|
+### Теперь проведем те же действия с помощью LINQ:
|
|
|
+```
|
|
|
+string[] students = {"Женя", "Моисей", "Влада", "Амир", "Маша", "Катя"};
|
|
|
+
|
|
|
+var selectedStudents = from t in students
|
|
|
+ where t.ToUpper().StartsWith("М")
|
|
|
+ orderby t
|
|
|
+ select t;
|
|
|
+
|
|
|
+foreach (string s in selectedStudents)
|
|
|
+ Console.WriteLine(s);
|
|
|
+```
|
|
|
+```
|
|
|
+Маша
|
|
|
+Моисей
|
|
|
+```
|
|
|
+## Методы расширения LINQ
|
|
|
+```
|
|
|
+string[] students = { "Женя", "Моисей", "Влада", "Амир", "Маша", "Катя" };
|
|
|
+
|
|
|
+var selectedStudents = students
|
|
|
+ .Where(t=>t.ToUpper().StartsWith("М"))
|
|
|
+ .OrderBy(t => t);
|
|
|
+
|
|
|
+foreach (string s in selectedStudents)
|
|
|
+ Console.WriteLine(s);
|
|
|
+```
|
|
|
+```
|
|
|
+Маша
|
|
|
+Моисей
|
|
|
+```
|
|
|
+## Фильтрация
|
|
|
+### Фильтрация с помощью операторов LINQ:
|
|
|
+```
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Program
|
|
|
{
|
|
|
- Console.WriteLine("Совпадений не найдено");
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ int[] grades = { 1, 2, 3, 4, 5, 6, 7 };
|
|
|
+
|
|
|
+ var lowGrades = grades.Where(grade => grade < 5);
|
|
|
+
|
|
|
+ Console.WriteLine("Оценки меньше '5':");
|
|
|
+ foreach (var grade in lowGrades)
|
|
|
+ {
|
|
|
+ Console.WriteLine(grade);
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
```
|
|
|
```
|
|
|
-тупогуб
|
|
|
-тупогубенький
|
|
|
-тупа
|
|
|
+1
|
|
|
+2
|
|
|
+3
|
|
|
+4
|
|
|
```
|
|
|
-## Поиск с группами
|
|
|
+## Выборка сложных объектов
|
|
|
+### Создадим набор студентов и выберем из них тех, которым меньше 23 лет:
|
|
|
```
|
|
|
-string text = "One car red car blue car";
|
|
|
-string pat = @"(\w+)\s+(car)";
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
|
|
|
-Regex r = new Regex(pat, RegexOptions.IgnoreCase);
|
|
|
+ public Student(string name, int age)
|
|
|
+ {
|
|
|
+ Name = name;
|
|
|
+ Age = age;
|
|
|
+ }
|
|
|
+}
|
|
|
|
|
|
-Match m = r.Match(text);
|
|
|
-int matchCount = 0;
|
|
|
-// можно искать не одно вхождение, а несколько
|
|
|
-while (m.Success)
|
|
|
+class Program
|
|
|
{
|
|
|
- Console.WriteLine("Match"+ (++matchCount));
|
|
|
- // тут можно было бы перебирать по длине массива Groups,
|
|
|
- // но мы по своему шаблону и так знаем, что у нас две подгруппы
|
|
|
- for (int i = 1; i <= 2; i++)
|
|
|
+ static void Main()
|
|
|
{
|
|
|
- Console.WriteLine($"Group {i}='{m.Groups[i]}'");
|
|
|
+ List<Student> users = new List<Student>
|
|
|
+ {
|
|
|
+ new Student("Влада", 23),
|
|
|
+ new Student("Саня", 19),
|
|
|
+ new Student("Амир", 21),
|
|
|
+ new Student("Маша", 24)
|
|
|
+ };
|
|
|
+
|
|
|
+ var selectedUsers = users.Where(u => u.Age <23);
|
|
|
+ foreach (Student user in selectedUsers)
|
|
|
+ {
|
|
|
+ Console.WriteLine($"{user.Name}, - {user.Age}");
|
|
|
+ }
|
|
|
}
|
|
|
- // поиск следующей подстроки соответсвующей шаблону
|
|
|
- m = m.NextMatch();
|
|
|
}
|
|
|
```
|
|
|
```
|
|
|
-Match1
|
|
|
-Group 1='One'
|
|
|
-Group 2='car'
|
|
|
-Match2
|
|
|
-Group 1='red'
|
|
|
-Group 2='car'
|
|
|
-Match3
|
|
|
-Group 1='blue'
|
|
|
-Group 2='car'
|
|
|
+Саня, - 19
|
|
|
+Амир, - 21
|
|
|
```
|
|
|
-## Параметр RegexOptions
|
|
|
-### 示例1
|
|
|
+## Сложные фильтры
|
|
|
+### Для создания запроса применяется метод SelectMany:
|
|
|
```
|
|
|
-string s = "Бык тупогуб, тупогубенький бычок, у быка губа бела была тупа";
|
|
|
-Regex regex = new Regex(@"\w*губ\w*");
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+ public List<string> Languages { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ List<Student> users = new List<Student>
|
|
|
+ {
|
|
|
+ new Student { Name = "Арсен", Age = 21, Languages = new List<string> { "английский", "китайский" } },
|
|
|
+ new Student { Name = "Вася", Age = 24, Languages = new List<string> { "испанский", "японский" } },
|
|
|
+ new Student { Name = "Глория", Age = 23, Languages = new List<string> { "китайский", "немецкий" } },
|
|
|
+ new Student { Name = "Стеша", Age = 29, Languages = new List<string> { "итальянский", "английский"} }
|
|
|
+ };
|
|
|
+
|
|
|
+ var selectedUsers = users
|
|
|
+ .SelectMany(u => u.Languages,
|
|
|
+ (u, l) => new { Student = u, Lang = l })
|
|
|
+ .Where(u => u.Lang == "китайский" && u.Student.Age < 25)
|
|
|
+ .Select(u => u.Student);
|
|
|
+
|
|
|
+ Console.WriteLine("Студенты, изучающие китайский младше 25 лет:");
|
|
|
+ foreach (var user in selectedUsers)
|
|
|
+ {
|
|
|
+ Console.WriteLine($"{user.Name}, возраст: {user.Age}");
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
```
|
|
|
```
|
|
|
-Process finished with exit code 0.
|
|
|
+Студенты, изучающие китайский младше 25 лет:
|
|
|
+Арсен, возраст: 21
|
|
|
+Глория, возраст: 23
|
|
|
```
|
|
|
-### 例子2
|
|
|
+## Проекция
|
|
|
+### нам нужен не весь объект, а только его свойство Name:
|
|
|
```
|
|
|
-string s = "456-435-2318";
|
|
|
-Regex regex = new Regex(
|
|
|
- @"\d{3}-\d{3}-\d{4}");
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ List<Student> users = new List<Student>();
|
|
|
+ users.Add(new Student { Name = "Мадина", Age = 20 });
|
|
|
+ users.Add(new Student { Name = "Максим", Age = 23 });
|
|
|
+ users.Add(new Student { Name = "Макар", Age = 21 });
|
|
|
+
|
|
|
+ var names = users.Select(u => u.Name);
|
|
|
+
|
|
|
+ foreach (string n in names)
|
|
|
+ Console.WriteLine(n);
|
|
|
+ }
|
|
|
+}
|
|
|
```
|
|
|
```
|
|
|
-Process finished with exit code 0.
|
|
|
+Мадина
|
|
|
+Максим
|
|
|
+Макар
|
|
|
```
|
|
|
-## Проверка на соответствие строки формату
|
|
|
+### можно создать объекты другого типа, в том числе анонимного:
|
|
|
```
|
|
|
-string pattern = @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
|
|
|
- @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$";
|
|
|
-while (true)
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
{
|
|
|
- Console.WriteLine("Введите адрес электронной почты");
|
|
|
- string email = Console.ReadLine();
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ List<Student> users = new List<Student>();
|
|
|
+ users.Add(new Student { Name = "Мадина", Age = 20 });
|
|
|
+ users.Add(new Student { Name = "Максим", Age = 23 });
|
|
|
+ users.Add(new Student { Name = "Макар", Age = 21 });
|
|
|
|
|
|
- if (Regex.IsMatch(email, pattern, RegexOptions.IgnoreCase))
|
|
|
+ var items = users.Select(u => new {
|
|
|
+ FirstName = u.Name,
|
|
|
+ DateOfBirth = DateTime.Now.Year - u.Age
|
|
|
+ });
|
|
|
+
|
|
|
+ foreach (var n in items)
|
|
|
+ Console.WriteLine($"{n.FirstName} - {n.DateOfBirth}");
|
|
|
+ }
|
|
|
+}
|
|
|
+```
|
|
|
+```
|
|
|
+Мадина - 2004
|
|
|
+Максим - 2001
|
|
|
+Макар - 2003
|
|
|
+```
|
|
|
+## Переменые в запросах и оператор let
|
|
|
+```
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ List<Student> students = new List<Student>()
|
|
|
+ {
|
|
|
+ new Student
|
|
|
+ {
|
|
|
+ Name = "Алеша", Age = 19
|
|
|
+ },
|
|
|
+ new Student
|
|
|
+ {
|
|
|
+ Name = "Гоша", Age = 22
|
|
|
+ }
|
|
|
+ };
|
|
|
+
|
|
|
+ var people = from u in students
|
|
|
+ let name = "Mr. " + u.Name
|
|
|
+ select new
|
|
|
+ {
|
|
|
+ Name = name,
|
|
|
+ Age = u.Age
|
|
|
+ };
|
|
|
+ foreach (var person in people)
|
|
|
+ {
|
|
|
+ Console.WriteLine($" {person.Name}");
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+```
|
|
|
+```
|
|
|
+ Mr. Алеша
|
|
|
+ Mr. Гоша
|
|
|
+```
|
|
|
+## Выборка из нескольких источников
|
|
|
+```
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Lesson
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+}
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
{
|
|
|
- Console.WriteLine("Email подтвержден");
|
|
|
- break;
|
|
|
+
|
|
|
+ List<Student> users = new List<Student>()
|
|
|
+ {
|
|
|
+ new Student { Name = "Влад", Age = 19 },
|
|
|
+ new Student { Name = "Влада", Age = 21 }
|
|
|
+ };
|
|
|
+ List<Lesson> lessons = new List<Lesson>()
|
|
|
+ {
|
|
|
+ new Lesson
|
|
|
+ {
|
|
|
+ Name = "math"
|
|
|
+ },
|
|
|
+ new Lesson
|
|
|
+ {
|
|
|
+ Name = "psychology"
|
|
|
+ },
|
|
|
+ };
|
|
|
+
|
|
|
+ var people = from student in users
|
|
|
+ from lesson in lessons
|
|
|
+ select new { Name = student.Name, Lesson = lesson.Name };
|
|
|
+
|
|
|
+ foreach (var p in people)
|
|
|
+ Console.WriteLine($"{p.Name} - {p.Lesson}");
|
|
|
}
|
|
|
- else
|
|
|
+}
|
|
|
+```
|
|
|
+```
|
|
|
+Влад - math
|
|
|
+Влад - psychology
|
|
|
+Влада - math
|
|
|
+Влада - psychology
|
|
|
+```
|
|
|
+## Сортировка
|
|
|
+```
|
|
|
+using System;
|
|
|
+using System.Linq;
|
|
|
+
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
{
|
|
|
- Console.WriteLine("Некорректный email");
|
|
|
+
|
|
|
+ List<Student> users = new List<Student>()
|
|
|
+ {
|
|
|
+ new Student { Name = "Арсен", Age = 18 },
|
|
|
+ new Student { Name = "Семен", Age = 29 },
|
|
|
+ new Student { Name = "Полина", Age = 27 },
|
|
|
+ new Student { Name = "Кирилл", Age = 21 }
|
|
|
+ };
|
|
|
+
|
|
|
+ var sortedStudent = users.OrderByDescending(u => u.Name);
|
|
|
+
|
|
|
+ foreach (Student u in sortedStudent)
|
|
|
+ Console.WriteLine(u.Name);
|
|
|
}
|
|
|
}
|
|
|
```
|
|
|
```
|
|
|
-Введите адрес электронной почты
|
|
|
-dkljfsljkf@gmail.com
|
|
|
-Email подтвержден
|
|
|
+Семен
|
|
|
+Полина
|
|
|
+Кирилл
|
|
|
+Арсен
|
|
|
+```
|
|
|
+## Множественные критерии сортировки
|
|
|
```
|
|
|
-## Замена и метод Replace
|
|
|
+class Student
|
|
|
+{
|
|
|
+ public string Name { get; set; }
|
|
|
+ public int Age { get; set; }
|
|
|
+}
|
|
|
+
|
|
|
+class Program
|
|
|
+{
|
|
|
+ static void Main()
|
|
|
+ {
|
|
|
+ List<Student> users = new List<Student>()
|
|
|
+ {
|
|
|
+ new Student { Name = "Амир", Age = 23 },
|
|
|
+ new Student { Name = "Егор", Age = 30 },
|
|
|
+ new Student { Name = "Настя", Age = 21 },
|
|
|
+ new Student { Name = "Анжела", Age = 19 }
|
|
|
+ };
|
|
|
+
|
|
|
+ var result = users
|
|
|
+ .OrderBy(u => u.Name)
|
|
|
+ .ThenBy(u => u.Age);
|
|
|
+
|
|
|
+ foreach (Student u in result)
|
|
|
+ Console.WriteLine($"{u.Name} - {u.Age}");
|
|
|
+ }
|
|
|
+}
|
|
|
```
|
|
|
-string s = "Мама мыла раму. ";
|
|
|
-string pattern = @"\s+";
|
|
|
-string target = " ";
|
|
|
-Regex regex = new Regex(pattern);
|
|
|
-string result = regex.Replace(s, target);
|
|
|
```
|
|
|
+Амир - 23
|
|
|
+Анжела - 19
|
|
|
+Егор - 30
|
|
|
+Настя - 21
|
|
|
```
|
|
|
-Process finished with exit code 0.
|
|
|
-```
|