[英]How to select all from array1 which contains the id from array2?
I have a linq statement which includes a Contain() method. 我有一个linq语句,其中包含一个Contain()方法。 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. 我正在使用它,以便可以从名称不为null的数组中选择所有对象,而仅从array1中包含对象array2中包含相同名称的对象中选择对象。
I have managed to return the result but its displaying true or false where as I need the object values. 我设法返回了结果,但是在需要对象值的地方显示了true或false。
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: 如果不使用select语句,则会得到对象:
[
{
"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. initalName在getNames数组中不存在,因此需要删除。 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"
]
The problem is, that in this LINQ expression, at the end you are selecting a Bool as an output. 问题在于,在此LINQ表达式中,最后您选择的是Bool作为输出。 (.Contains() returns a bool). (.Contains()返回布尔值)。 From this reason, your expression will retunr a list of Bool. 因此,您的表达式将重新调整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: 要满足您的需求,只需将.Select()替换为.Where(),将执行预期的过滤并保持原始对象不变(不会进行任何投影),您将获得预期的结果:
response.items
.Where(n => n.name != null)
.DistinctBy(x => x.name)
.Where(a => getNames.Contains(a.initialName))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.