我想知道是否有人可以帮助我,基本上我试图使用linq压扁列表。在列表中是一组电话号码,我不知道要做的是计算阵列的大小并将每个电话号码添加为唯一的列表值。
var FlatenedList = from x in result
where x.ID != null
orderby x.ID
select new
{
AccountNumber = x.AccountNumber,
Balance = x.Balance,
BillToCompanyName = x.BillToContact.CompanyName,
BillToName = x.BillToContact.Name,
BillToPhoneNumber1 = x.BillToContact.PhoneNumbers[0].Number == null ? String.Empty : (x.BillToContact.PhoneNumbers[0].Number),
BillToPhoneNumber2 = x.BillToContact.PhoneNumbers[1].Number == null ? String.Empty : (x.BillToContact.PhoneNumbers[1].Number),
BillToPhoneNumber3 = x.BillToContact.PhoneNumbers[2].Number == null ? String.Empty : (x.BillToContact.PhoneNumbers[2].Number),
};
答案 0 :(得分:2)
如果我理解正确,这就是你所需要的: -
var result = accounts.OrderBy(x => x.Id)
.Select(x => new
{
AccountNumber = x.AccountNumber,
Balance = x.Balance,
BillToCompanyName = x.BillToContact.CompanyName,
BillToName = x.BillToContact.Name,
PhoneNumbersCount = x.BillToContact.PhoneNumbers.Count(),
//All phone numbers count including null
PhoneNumbersList = x.BillToContact.PhoneNumbers
.Select(z => z.Number ?? String.Empty).ToList()
});
您可以查看我使用了一些示例数据的Fiddle,并告诉我这是否是您要查找的内容。
答案 1 :(得分:0)
可能你应该试试下面的东西,我还没有编译它,但这可能有效
var FlatenedList = from x in result
where x.ID != null
orderby x.ID
select new
{
AccountNumber = x.AccountNumber,
Balance = x.Balance,
BillToCompanyName = x.BillToContact.CompanyName,
BillToName = x.BillToContact.Name,
BillToPhoneNumber = x.BillToContact.PhoneNumbers.ToList().Where(num=>num.Number !=null).Select(num=>num)
};
答案 2 :(得分:0)
我认为你需要一个Expand Object。
以下是如何为一个项目执行此操作:
var FlattenedItem = new ExpandoObject();
for(int i = 0; i < x.BillToContact.PhoneNumbers.length; i++) {
// You will have to cast FlattenedItem to an IDictionary to add items
((IDictionary<string, object>)FlattenedItem).Add("BillToPhoneNumber" + i, x.BillToContact.PhoneNumbers[i]);
}
// This is your first phonenumber
var firstPhoneNumber = FlattenedItem.BillToPhoneNumber0;
查看此答案以获取更多信息: Creating an anonymous type dynamically?