Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * NuGet:
- *
- * Microsoft.EntityFrameworkCore (3.1.3)
- * Microsoft.EntityFrameworkCore.InMemory (3.1.3)
- * Microsoft.EntityFrameworkCore.Tools (3.1.3)
- */
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
- using System;
- using System.Collections.Generic;
- using System.Dynamic;
- using System.Linq;
- namespace ConsoleApp48
- {
- class Program
- {
- static void Main(string[] args)
- {
- var test = new Test();
- test.TEst1();
- Console.ReadKey();
- }
- }
- public class Test
- {
- static IEnumerable<string> GetBenchData()
- {
- var rn = Environment.NewLine;
- yield return $"ФИО:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
- yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
- yield return $"ФИО:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Возраст:22";
- yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Полных лет:22";
- yield return $"ФИО:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
- yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
- yield return $"ФИО:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Возраст:22";
- yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Полных лет:22";
- }
- public void TEst1()
- {
- foreach (var data in GetBenchData())
- {
- dynamic obj = new MultiObject(data);
- Console.WriteLine($"FullName: {obj.FullName}, Phone: {obj.Phone}, Age:{obj.Age}");
- }
- }
- }
- public class MultiObject : DynamicObject
- {
- private readonly HabraDbContext _context;
- private readonly IRawStringParser _parser;
- private readonly Dictionary<string, string> keyValues;
- public MultiObject(string rawText)
- {
- _context = IoC.GetService<HabraDbContext>();
- _parser = IoC.GetService<IRawStringParser>();
- keyValues = _parser.ParseWithLinq(rawText);
- }
- //используется
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- var properties = _context.ContactMapSchemas.Where(x => x.Property == binder.Name).ToDictionary(x => x.Key, x => x.Property);
- result = keyValues.FirstOrDefault(x => properties.ContainsKey(x.Key)).Value;
- return true;
- }
- //не используется
- public override bool TryConvert(ConvertBinder binder, out object result)
- {
- var properties = _context.ContactMapSchemas.Where(x => x.EntityName == binder.Type.FullName).ToDictionary(x => x.Key, x => x.Property);
- result = Activator.CreateInstance(binder.Type);
- foreach (var item in keyValues)
- {
- if (properties.ContainsKey(item.Key))
- {
- var prop = result.GetType().GetProperty(properties[item.Key]);
- prop.SetValue(result, Convert.ChangeType(item.Value, prop.PropertyType));
- }
- }
- return true;
- }
- }
- #region DB
- public class ContactMapSchema
- {
- public Guid Id { get; set; }
- public string EntityName { get; set; }
- public string Key { get; set; }
- public string Property { get; set; }
- }
- public class Contact
- {
- public string FullName { get; set; }
- public string Phone { get; set; }
- public int Age { get; set; }
- }
- public class HabraDbContext : DbContext
- {
- private static readonly string _contactAssemblyName = typeof(Contact).FullName;
- private static readonly string _contactPhoneAssemblyName = nameof(Contact.Phone);
- private static readonly string _contactFullNameAssemblyName = nameof(Contact.FullName);
- private static readonly string _contactAgeAssemblyName = nameof(Contact.Age);
- public DbSet<ContactMapSchema> ContactMapSchemas { get; set; }
- public HabraDbContext(DbContextOptions<HabraDbContext> options) : base(options) { Database.EnsureCreated(); }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- builder.Entity<ContactMapSchema>().HasKey(x => x.Id);
- builder.Entity<ContactMapSchema>().HasData(
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Телефон", Property = _contactPhoneAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Контактный телефон", Property = _contactPhoneAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Тел.", Property = _contactPhoneAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "ФИО", Property = _contactFullNameAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Фамилия Имя Отчество", Property = _contactFullNameAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Имя", Property = _contactFullNameAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Возраст", Property = _contactAgeAssemblyName },
- new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Полных лет", Property = _contactAgeAssemblyName });
- }
- }
- #endregion
- #region Service
- public interface IRawStringParser
- {
- Dictionary<string, string> ParseWithLinq(string rawData, string keyValueDelimiter = ":");
- Dictionary<string, string> ParseWithoutLinq(string rawData, string keyValueDelimiter = ":");
- }
- public class DefaultRawStringParser : IRawStringParser
- {
- public Dictionary<string, string> ParseWithLinq(string rawData, string keyValueDelimiter = ":") =>
- rawData?.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
- .Select(x => x.Split(keyValueDelimiter))
- .Select(x => x.Length == 2 ? new { Key = x[0], Value = x[1] } : new { Key = "", Value = "" })
- .Where(x => !string.IsNullOrEmpty(x.Key)).ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary<string, string>();
- public Dictionary<string, string> ParseWithoutLinq(string rawData, string keyValueDelimiter = ":")
- {
- var result = new Dictionary<string, string>();
- foreach (var row in rawData?.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
- {
- var split = row.Split(keyValueDelimiter);
- if (split.Length == 2) result.Add(split[0], split[1]);
- }
- return result;
- }
- }
- public static class IoC
- {
- public static ServiceProvider Provider { get; set; }
- static IoC()
- {
- var services = new ServiceCollection();
- services.AddDbContext<HabraDbContext>(x => x.UseInMemoryDatabase(databaseName: "memoryDB"));
- services.AddSingleton<IRawStringParser, DefaultRawStringParser>();
- Provider = services.BuildServiceProvider();
- }
- internal static T GetService<T>()
- {
- return Provider.GetService<T>();
- }
- }
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement