在列表中的属性上使用.Contains() [英] Using .Contains() on a property in a list

查看:68
本文介绍了在列表中的属性上使用.Contains()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动清单.在Activity类中是一个ID属性(出于参数考虑,是Guid).我想检查此列表中是否包含带有Guid的活动".而不是这样:

I have a List of Activity. In the Activity class is an ID property (a Guid for arguments sake). I want to check if this list has an Activity in it with a Guid I have. Rather than this:

foreach(Activity activity in ActivityList)
{
    if(activity.Id == GuidToCompare)
        //Code here
}

如果只有一个Guid列表(而不是Activity的列表)并使用.Contains(),是否有更有效的方法来达到相同的结果?

Is there a more efficient way to achieve the same result as I could if I were to have just a list of Guids (instead of a list of Activity's) and to use .Contains()?

我有一个名为ActivityAndPO的结构的列表.在这个结构中是一个Guid. 我有一份PO的清单.在PO类中是Guid.

I've got a list of a struct called ActivityAndPO. In this struct is a Guid. I have a list of PO's. In the PO class is a Guid.

我想遍历ActivityAndPO列表中所有对象,而Guid存在于PO列表中.

I want to loop through all of objects in the the ActivityAndPO list where the Guid's exist in the list of PO's.

推荐答案

可以.

foreach(Activity activity in ActivityList.Where(a => a.Id == GuidToCompare) )
{        
    //Code here
}

但是由于Id表示最多会有1个活动:

But since Id implies there will be at most 1 activity:

//var act = ActivityList.Where(a => a.Id == GuidToCompare).SingleOrDefault(); // clearer
var act = ActivityList.SingleOrDefault(a => a.Id == GuidToCompare);          // shorter
if (act != null)
{
    //Code here
}

这篇关于在列表中的属性上使用.Contains()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆