which in the second list im trying to create a relationship, however if it cant a match, how do I ignore and not add an item?
var clientData = File.ReadAllLines(txtClients.Text)
.Skip(1)
.Select(x => x.Split(','))
.Select(x => new Client()
{
ClientTempId = x[0],
Email = x[1],
FirstName = x[2],
LastName = x[3],
AccountId = accountId
});
var orderData = File.ReadAllLines(txtOrders.Text)
.Skip(1)
.Select(x => x.Split(','))
.Select(x => new Order()
{
OrderTempId = x[0],
ClientId = clientData.FirstOrDefault(c=>c.ClientTempId == x[1]).Id ==string.Empty?"Error here!!":x[1],
//How do I handle errors, if client does not exist, or row is in wrong format? dont want to break code just want a list or issues
Name = x[3],
AccountId = accountId
});
You can return null
instead and then filter those out:
var orderData = File.ReadAllLines(txtOrders.Text)
.Skip(1)
.Select(x => x.Split(','))
.Select(x =>
{
// do your check here, and return null
if (clientData.FirstOrDefault(c => c.ClientTempId == x[1]) == null)
return null;
// otherwise return the normal Order object
return new Order()
{
OrderTempId = x[0],
ClientId = x[1],
Name = x[3],
AccountId = accountId
};
})
// then filter out null values
.Where(x => x != null);
Once that is covered, as EZI pointed out in the comments, your actual check is quite expensive. You can make it more efficient by turning your clientData
into a dictionary:
var clientDataDictionary = clientData.ToDictionary(c => c.ClientTempId);
Then, you can do the lookup above in constant time:
if (clientDataDictionary.ContainsKey(x[1]))
return null;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.