通过列表进行一般迭代

时间:2019-06-26 07:40:55

标签: c# list iteration ienumerable

我一直在构建电子邮件生成器功能。它起初是一个正则表达式功能,但很快就移到了反射上,以使其尽可能通用。想法是让电子邮件生成器功能从messagedata类中提取信息。它开始只是一个简单的任务,因为该功能只需要更改一些静态项,但是随着该功能变得越来越复杂并且模板被发送出所需的信息表,那么我构建的功能还不够。

我已经扩展了该功能,以使用foreach循环遍历模板并基于messageData类中的列表替换文本。我一直在尝试在messageData中创建列表,以将其实现到emailGenerator函数中。 我有:

string value = match.Groups["value"].Value;
// Code removed to shorten length
var items = (IEnumerable) value;

但是它不是从messageData类中收集信息。我在想,也许我需要将值放入列表中?

这是EmailGenerator函数:

    public class EmailGenerator : IEmailGenerator
    {
        private string mergeTemplate(string template, object obj)
        {
            var operationMatches = operationParser.Matches(template).Cast<Match>().Reverse().ToList();
            foreach (var match in operationMatches)
            {
                string operation = match.Groups["operation"].Value;
                string value = match.Groups["value"].Value;
                var propertyInfo = obj.GetType().GetProperty(value);

                object dataValue = propertyInfo.GetValue(obj, null);

                if (operation == "endforeach")
                {
                    string foreachToken = "$foreach " + value + "$";
                    var startIndex = template.LastIndexOf(foreachToken, match.Index);
                    var templateBlock = template.Substring(startIndex + foreachToken.Length, match.Index - startIndex - foreachToken.Length);
                    var items = (IEnumerable) value;

                    string blockResult = "";

                    foreach (object item in items)
                    {
                        blockResult += this.mergeTemplate(templateBlock, item);
                    }

                    template = template.Remove(startIndex, match.Index - startIndex).Insert(startIndex, blockResult);
                }
            }
    }

这是messageData类。它从DTO获取信息。 **编辑:删除了不必要的代码。

public class messageData : IMailObject
    {
        public List<messageItemData> Items
        {
            get
            {
                var items = new List<messageItemData>();
                foreach (var docDTO in this.recipientDTO.InfoList)
                {
                    items.Add(new messageItemData(docDTO));

                }
            }
        }
    }

    public class messageItemData
    {
        // Properties
    }

我要完成的工作是使emailGenerator函数具有足够的通用性,以便以后可以用于其他电子邮件模板,并从messageData类及其包含的列表中收集替换信息。

1 个答案:

答案 0 :(得分:0)

所以,我终于找到了答案。该代码可以正常工作99%。就像将var items = (IEnumerable) value;更改为var items = (IEnumerable) dataValue;

一样简单