.NET 4.x Найти повторяющееся значение и вывести имя свойства - C#
Формулировка задачи:
Имеется
Вопрос: как узнать по каким свойствам совпадают классы в коллекции, вывести имя свойства совпадающих и значение свойства. Т.е. найти дубляж по двум свойствам и вывести этот дубляж...да хоть в консоль)))
public class Part
{
public string Designation {get; set;}
public string Name {get; set;}
public int Count {get; set;}
public Part (string _name, string _designation, int _count)
{
Name = _name;
Designation = _designation;
Count = _count;
}
}
//......................
public ObservableCollection<Part> PartCollection { get; set; }
PartCollection.Add(new Part("Деталька","АБВГ", 3);
PartCollection.Add(new Part("Деталька","АБВ", 1);
PartCollection.Add(new Part("Деталька","АБВГ",43);
//......................Решение задачи: «.NET 4.x Найти повторяющееся значение и вывести имя свойства»
textual
Листинг программы
using System;
using System.Collections.ObjectModel;
using System.Reflection;
namespace ConsoleApplication1
{
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObservableCollection<Part> PartCollection = new ObservableCollection<Part>();
PartCollection.Add(new Part("Деталька", "АБВГ", 3));
PartCollection.Add(new Part("Деталька", "АБВ", 1));
PartCollection.Add(new Part("Деталька", "АБВГ", 43));
string result = "";
for (int i = 0; i < PartCollection.Count; i++)
for (int j = i + 1; j < PartCollection.Count; j++)
{
var part1 = PartCollection[i];
var part2 = PartCollection[j];
string matches = Matches(part1, part2);
if (!string.IsNullOrEmpty(matches))
result += $"Для Part {part1.Name} и Part {part2.Name} найдены следующие совпадения:\n{matches}\n";
}
Console.WriteLine(result);
}
public class Part
{
public string Designation { get; set; }
public string Name { get; set; }
public int Count { get; set; }
public Part(string _name, string _designation, int _count)
{
Name = _name;
Designation = _designation;
Count = _count;
}
}
private static string Matches(Part part1, Part part2)
{
string result = "";
int matches = 0;
var pi = typeof(Part).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.SetProperty);
foreach (var p in pi)
if (p.GetValue(part1).Equals(p.GetValue(part2)))
{
matches++;
result += $"Имя свойства: {p.Name}; Значение свойства: {p.GetValue(part1)}\n";
};
if (matches >= 2) return result;
else return "";
}
}
}
}