正如标题所述,我正在尝试创建一个linq扩展方法,该方法允许我仅在一个对象属性中运行一个函数,但是不幸的是,我对此并没有做太多的事情,我真正拥有的只是(我相信)是执行此操作的方法的外壳:
public static IQueryable<T> ChangeProperty<T>(this IQueryable<T> source, Expression<Func<T, string>> selector, Func<T,T> method)
{
//Placeholder
return Enumerable.Empty<T>().AsQueryable();
}
对于上下文,我具有此功能,该功能可将所有html元素从字符串中剥离:
public static string RemoveUnwantedTags(string data)
{
if (string.IsNullOrEmpty(data)) return string.Empty;
var document = new HtmlDocument();
document.LoadHtml(data);
var acceptableTags = new string[] { "strong", "em", "u" };
var nodes = new Queue<HtmlNode>(document.DocumentNode.SelectNodes("./*|./text()"));
while (nodes.Count > 0)
{
var node = nodes.Dequeue();
var parentNode = node.ParentNode;
if (acceptableTags.Contains(node.Name) || node.Name == "#text") continue;
var childNodes = node.SelectNodes("./*|./text()");
if (childNodes != null)
{
foreach (var child in childNodes)
{
nodes.Enqueue(child);
parentNode.InsertBefore(child, node);
}
}
parentNode.RemoveChild(node);
}
var htmlFormattingTags = new [] {" ","&tbsp;"};
if (!htmlFormattingTags.Any(x=>document.DocumentNode.InnerText.Contains(x))) return document.DocumentNode.InnerHtml;
var template = document.DocumentNode.InnerText;
foreach (var tag in htmlFormattingTags)
{
template = template.Replace(tag, " ");
}
return template;
}
我正在使用EF捕获数据,并且我需要针对4个不同的表使用此函数(因此希望使其具有通用性)。所以,如果我说这节课:
public partial class EmailTemplate : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ID;
private string _tenant;
private string _TemplateName;
private bool _HTML;
private string _Body;
private string _Images;
private string _Subject;
private System.Nullable<bool> _SMS;
private System.Guid _rowguid;
private System.Nullable<int> _OverrideServer;
^^因为是EF类而被截断了
我希望能够做到
dc.EmailTemplates
.Where(x=>x.Body != null)
.ChangeProperty(x=>x.Body, RemoveUnwantedTags)
.ToList();
答案 0 :(得分:0)
您可以只在每个元素上调用t.Body = RemoveUnwantedTags(t.Body)
。
dc.EmailTemplates
.Where( t => t.Body != null)
.ToList()//Load from db
.ForEach( t => t.Body = RemoveUnwantedTags(t.Body)) //This is done in memory, not in the database