user3515765 user3515765 - 3 days ago 5
C# Question

How to select all from array1 which contains the id from array2?

I have a linq statement which includes a Contain() method. I am using this so that I can select all from an array where name is not null but only select the objects from the array1 that contains the same name in object array2.

I have managed to return the result but its displaying true or false where as I need the object values.

The code

var response = JsonConvert.DeserializeObject<FamilyNames>(result);
List<object> data = new List<object>();

ClassName className = new ClassName();

object [] getNames = className.GetType()
.GetProperties()
.Select(p =>
{
object value = p.Name;
return value == null ? null : value.ToString();
})
.ToArray();

foreach (var obj in response.items.Where(n => n.name != null).DistinctBy(x => x.name).Select(a => getNames.Contains(a.initialName)))
{
data.Add(obj);
}
client.Dispose();
return Json(data, JsonRequestBehavior.AllowGet);
}


The result is :

["True","False","True"]


If I don't use the select statement then I get my objects:

[
{
"initalName": "BD",
"firstName": "Bob",
"LastName": "Dilan"
},
{
"initalName": "HT",
"firstName": "Harry", // the initialName doesn't exist in list so need to remove this object
"LastName": "Thomas"
},
{
"initalName": "LJ",
"firstName": "Lindsey",
"LastName": "Jones"
}
]


The initalName is not present in getNames array so needs to be removed. Any advice would be much appreciated, especially on the approach. The desired result would be:

[
{
"initalName": "BD",
"firstName": "Bob",
"LastName": "Dilan"
},
{
"initalName": "LJ",
"firstName": "Lindsey",
"LastName": "Jones"
]

Answer

The problem is, that in this LINQ expression, at the end you are selecting a Bool as an output. (.Contains() returns a bool). From this reason, your expression will retunr a list of Bool.

response.items
.Where(n => n.name != null)
.DistinctBy(x => x.name)
.Select(a => getNames.Contains(a.initialName))

To acheave what you want, simply replace the .Select() with a .Where(), what will do the intended filtering and keep the original objects as they are, (will not do any projection) and you will get the expected outcome:

response.items
.Where(n => n.name != null)
.DistinctBy(x => x.name)
.Where(a => getNames.Contains(a.initialName))
Comments