我有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
现在我需要根据Field(父表)创建一个包含FieldIndex(子表)的字符串 采用以下格式。
我期望输出字符串按字段列(Parent)的顺序,如果有任何映射字段(在Child中)可用,那么它 应显示,所有其他值应替换为“$”符号..
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;
}
答案 0 :(得分: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));
}