Files
LeafWeb/Core/Utility/ParseInfoPropertyMatcher.cs
T

66 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Fasterflect;
namespace LeafWeb.Core.Utility
{
public class ParseInfoPropertyMatcher<T>
where T : new()
{
public IList<PropertyInfo> ParseInfoProperties { get; }
public ParseInfoPropertyMatcher()
{
ParseInfoProperties = GetParseInfoProperties();
}
private PropertyInfo[] GetParseInfoProperties()
{
var propertyInfos = typeof(T).Properties();
return propertyInfos.Where(p => AttributeExtensions.HasAttribute<ParseInfoAttribute>(p)).ToArray();
}
public virtual PropertyInfo MatchProperty(string title, int position)
{
return
ParseInfoProperties.FirstOrDefault(p => p.Attribute<ParseInfoAttribute>().IsTitleMatch(title)) ??
ParseInfoProperties.FirstOrDefault(p => p.Attribute<ParseInfoAttribute>().IsPositionMatch(position));
}
public virtual PropertyInfo MatchPropertyExact(string title, int position)
{
return
ParseInfoProperties
.FirstOrDefault(p =>
{
var attribute = p.Attribute<ParseInfoAttribute>();
return attribute.IsTitleMatch(title) && attribute.IsPositionMatch(position);
});
}
public virtual bool IsPropertiesTitlesMatch(string[] titles)
{
var propertyMatch = 0;
var propertyNoMatch = 0;
for (var i = 0; i < titles.Length; i++)
{
var title = titles[i];
var position = i + 1;
if (String.IsNullOrEmpty(title))
continue;
var property = MatchPropertyExact(title, position);
if (property != null)
propertyMatch++;
else
propertyNoMatch++;
}
return propertyMatch / (double)propertyNoMatch > .9;
}
}
}