首页 > 解决方案 > 使用拆分将字符串列表转换为对象列表

问题描述

我有一个字符串“obAttachmentTypes”列表,其中每个字符串如下所示:(ID|NAME|LEVEL)。我正在尝试将这些字符串转换为 AttachmentType 对象列表,以便更易于管理。我使用 .Select 函数来翻译字符串列表,但我在尝试拆分字符串时遇到了麻烦。我已经研究过使用 Split() 函数,但我不确定在这种情况下如何使用它。

List<KeywordDataSetItem> obAttachmentTypes = GetAttachmentTypes(app);

    var attachTypes = obAttachmentTypes
                .Select(at => new AttachmentType
                {
                    //use split here?
                    AttachmentTypeId = at.AlphaNumericValue.Split(''),
                    AttachmentTypeName = at.AlphaNumericValue.Split(''),
                    IsPopular = true,
                    AttachmentTypeLevel = at.AlphaNumericValue.Split(''),
                })
                .ToList();
            return attachTypes;

标签: c#split

解决方案


您需要先围绕管道符号拆分字符串,然后从结果数组中的不同索引中获取字符串。

    var attachTypes = obAttachmentTypes
                .Select(at => at.AlphaNumericValue.Split('|'))
                .Select(arr => new AttachmentType
                {
                    AttachmentTypeId = arr[0],
                    AttachmentTypeName = arr[1],
                    IsPopular = true,
                    AttachmentTypeLevel = arr[2],
                })
                .ToList();

推荐阅读