Is it possible to write the folowing using lambda(C#)
private static void GetRecordList(List<CustomerInfo> lstCustinfo)
{
for (int i = 1; i <= 5; i++)
{
if (i % 2 == 0)
lstCustinfo.Add(new CustomerInfo { CountryCode = "USA", CustomerAddress = "US Address" + i.ToString(), CustomerName = "US Customer Name" + i.ToString(), ForeignAmount = i * 50 });
else
lstCustinfo.Add(new CustomerInfo { CountryCode = "UK", CustomerAddress = "UK Address" + i.ToString(), CustomerName = "UK Customer Name" + i.ToString(), ForeignAmount = i * 80 });
}
}
List<CustomerInfo> lstCustinfo =
Enumerable.Range(1, 5).Select(i => (i % 2 == 0)
? new CustomerInfo { CountryCode = "USA", CustomerAddress = "US Address" + i.ToString(), CustomerName = "US Customer Name" + i.ToString(), ForeignAmount = i * 50 }
: new CustomerInfo { CountryCode = "UK", CustomerAddress = "UK Address" + i.ToString(), CustomerName = "UK Customer Name" + i.ToString(), ForeignAmount = i * 80 })
.ToList();
You must first define the selection, then add it to the incoming list:
var range = Enumerable.Range(1, 5);
var customers = from i in range
select (i % 2 == 0) ?
new CustomerInfo
{
CountryCode = "USA",
CustomerAddress = "US Address" + i,
CustomerName = "US Customer Name" + i,
ForeignAmount = i * 50
}
:
new CustomerInfo
{
CountryCode = "UK",
CustomerAddress = "UK Address" + i,
CustomerName = "UK Customer Name" + i,
ForeignAmount = i * 80
};
lstCustinfo.AddRange(customers);
Or perhaps even more explicit:
var range = Enumerable.Range(1, 5);
var usCustomers = from i in range
where i % 2 == 0
select new CustomerInfo
{
CountryCode = "USA",
CustomerAddress = "US Address" + i,
CustomerName = "US Customer Name" + i,
ForeignAmount = i * 50
};
var ukCustomers = from i in range
where i % 2 != 0
select new CustomerInfo
{
CountryCode = "UK",
CustomerAddress = "UK Address" + i,
CustomerName = "UK Customer Name" + i,
ForeignAmount = i * 80
};
lstCustinfo.AddRange(usCustomers.Union(ukCustomers));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With