I’m trying to write a LINQ query to show addresses that are related to users.
But I’d like to show addresses that reference invalid users as well. In this case, the fields related to the user should be set as null.
Glossary: “Invalid user”: not found in the users list.
Here is my code:
class Program
{
public static void Main(string[] args)
{
var users = GetUsers();
var addresses = GetAddresses();
var result = from address in addresses
from user in users
where user.Id == address.UserId
select new
{
address.Street,
address.Zipcode,
Id = address.UserId,
Name = user.Name,
Email = user.Email,
};
foreach(var item in result)
{
Console.WriteLine($"Street: {item.Street}");
Console.WriteLine($"Zipcode: {item.Zipcode}");
Console.WriteLine($"Id: {item.Id}");
Console.WriteLine($"Name: {item.Name}");
Console.WriteLine($"Email: {item.Email}");
}
}
static List<User> GetUsers()
{
const string usersData = "[{"id":"e135e5f9-64ed-4176-a543-ac7f09c15600","name":"John Doe","email":"[email protected]"},{"id":"d906db73-f711-4498-88b9-dc2d9d54ece5","name":"James Scott","email":"[email protected]"}]";
return JsonSerializer.Deserialize<List<User>>(usersData, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
}
static List<Address> GetAddresses()
{
const string addressData = "[{"street":"206 Hazel St","zipcode":"16853","city":"Milesburg","state":"PA", "country": "USA","userId":"e135e5f9-64ed-4176-a543-ac7f09c15600"},{"street":"208 Mill St","zipcode":"16853","city":"Milesburg","state":"PA", "country": "USA","userId":"d906db73-f711-4498-88b9-dc2d9d54ece5"},{"street":"100 Turnpike St","zipcode":"16853","city":"Milesburg","state":"PA", "country": "USA","userId":"b84b9728-b657-4db9-8af7-45789983d931"}]";
return JsonSerializer.Deserialize<List<Address>>(addressData, new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
}
}
internal class Address
{
public string Street { get; set; }
public string Zipcode { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public Guid UserId { get; set; }
}
internal class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
}
With the code above, addresses related to invalid users are ignored.
I was expecting to receive a List like so:
"Street": "206 Hazel St"
"Zipcode": "16853",
"Id": "e135e5f9-64ed-4176-a543-ac7f09c15600",
"Name": "John Doe",
"Email": "[email protected]"
},
{
"Street": "208 Mill St"
"Zipcode": "16853",
"Id": "d906db73-f711-4498-88b9-dc2d9d54ece5",
"Name": "James Scott",
"Email": "[email protected]"
},
{
"Street": "100 Turnpike St"
"Zipcode": "16853",
"Id": null,
"Name": null,
"Email": null
}]
New contributor
André Arruda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.