var resultNumbers = context.Numbers
.Where(n => requestNumbers.Contains(n.oldNumber) || requestNumbers.Contains(n.newNumber))
.Select(selector: n=> new StringCollection { n.oldNumber, n.newNumber}).ToArrayAsync();
I'm trying to get the single dimensional list for the above query, instead of 2 dimensional. I have list of numbers in the request as "requestNumbers", and need to check to see if the number is in either (onldNumber and newNumber) of the column and should return only the list of matched numbers, like if matched in oldNumber it should return only the n.oldNUmber not the other column values.
CodePudding user response:
I think that you are looking for SelectMany().
Projects each element of a sequence to an IEnumerable, flattens the resulting sequences into one sequence, and invokes a result selector function on each element therein.
Bellow, is a copy paste from an example from microsoft website: https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=net-5.0
class PetOwner
{
public string Name { get; set; }
public List<string> Pets { get; set; }
}
public static void SelectManyEx3()
{
PetOwner[] petOwners =
{ new PetOwner { Name="Higa",
Pets = new List<string>{ "Scruffy", "Sam" } },
new PetOwner { Name="Ashkenazi",
Pets = new List<string>{ "Walker", "Sugar" } },
new PetOwner { Name="Price",
Pets = new List<string>{ "Scratches", "Diesel" } },
new PetOwner { Name="Hines",
Pets = new List<string>{ "Dusty" } } };
// Project the pet owner's name and the pet's name.
var query =
petOwners
.SelectMany(petOwner => petOwner.Pets, (petOwner, petName) => new { petOwner, petName })
.Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
.Select(ownerAndPet =>
new
{
Owner = ownerAndPet.petOwner.Name,
Pet = ownerAndPet.petName
}
);
// Print the results.
foreach (var obj in query)
{
Console.WriteLine(obj);
}
}
// This code produces the following output:
//
// {Owner=Higa, Pet=Scruffy}
// {Owner=Higa, Pet=Sam}
// {Owner=Ashkenazi, Pet=Sugar}
// {Owner=Price, Pet=Scratches}
CodePudding user response:
Thanks @KlausGütter,
var resultNumbers = await context.Numbers
.Where(n => requestNumbers.Contains(n.oldNumber) || requestNumbers.Contains(n.newNumber))
.Select(selector: n => requestNumbers.Contains(n.oldNumber) ? n.oldNumber : n.newNumber)
.Distinct()
.ToArrayAsync()
.ConfigureAwait(continueOnCapturedContext: false);