0

我有 2 个包含以下数据的表

父表

S.No    Name     Fields
111    Parent1   title,fname,mname,lname,addr1,city,state,zip,county
112    Parent2    Address1,lname,firstName,suffix,countrycode,gender,zip,state,city,address2,email,phone

子表

S.No   mappingField   FieldIndex    ParentId
1      FirstName       1            111
2      LastName        3            111
3      AddressLine1    4            111
4      Country         8            111
5      LastName        1            112
6      FirstName       2            112
7      zip             6            112
8      state           7            112
9      workemail       10           112
10     workPhone       11           112

现在我需要使用以下格式的基于字段(父表)的 FieldIndex(子表)创建一个字符串。

我期望输出字符串按字段列(父级)的顺序排列,如果有任何映射字段(在子级)可用,那么它应该显示出来,并且所有其他值都应该用“$”符号替换。

ParentId 111 -- (9 fields)
$|FirstName|$|LastName|AddressLine1|$|$|$|Country

ParentId 112 --(12 fields)
$|LastName|FirstName|$|$|$|zip|state|$|$|workemail|workPhone

这是我的代码:

 private string mapping(ChildData, ParentData)
    {
        string[] fieldList = ChildData.Fields;

        var IndInfoList = new List<string>();

        string[] headerList = ParentData.Fields.Split(',');
        for (var i = 0; i < headerList.Length; i++)
        {           
            bool alreadyAdded = false;
            foreach (MyFields fields in fieldList)
            {
                if (i == ChildData.FieldIndex)
                {
                    IndInfoList.Add(ChildData.mappingField);
                }
                else
                {
                    if (!alreadyAdded)
                    {
                        IndInfoList.Add("$");
                        alreadyAdded = true;
                    }
                }
            }

        }
        string dataMapString = string.Join("|", IndInfoList);
        return dataMapString;
    }
4

1 回答 1

0

LINQ 可以为您简化很多工作,例如

var items = new List<string>(parentList.Count);
foreach (var p in parentList)
{
    var fields = p.Fields.Split(',');
    var childData = childList.Where(x => x.ParentId == p.Id).ToList();
    for (int i = 0; i <= fields.Length-1; i++)
    {
        var mappingField = childData.SingleOrDefault(x => x.FieldIndex == i).Select(x => x.mappingField);
        fields[i] = mappingField ?? "$";
    }
    items.Add(String.Join("|", fields));
}
于 2013-10-17T13:08:35.523 回答