0

我想在一个集合(继承另一个集合)中搜索一个属性值。

private ObservableCollection<User> userCollection = someData;

public class User
{
    public string Username { get; set; }
    public ObservableCollection<Department> Memberships { get; set; }
}

public class Department
{
    public string Name { get; set; }
}

//I can't use "Contains", because it requires an object of type "Department", but I don't have the object, just the string "Name" (in this case "MyDepartment")
var result = from usr in userCollection where (usr.Memberships.Contains("MyDepartment")) select usr;

你有什么建议吗?

4

3 回答 3

3

使用IEnumerable.Any来实现你想要的。

例如 :

(from usr in userCollection select usr).
               Any(x=>x.Username.Contains("MyDepartment"))
于 2012-07-23T08:41:20.743 回答
3

您可以使用.Any()onIEnumerable来实现您想要的。true如果集合中有一个或多个元素返回谓词,这将返回true

var result = from usr in userCollection 
             where usr.Memberships.Any(m => m.Name == "MyDepartment")
             select usr;
于 2012-07-23T08:42:10.747 回答
2

使用您的代码示例 - 您需要选择您正在检查的部门的等效部分到一个新集合中,然后您对它运行包含。

var result = from usr in userCollection where (usr.Memberships.Select(m=>m.Name).Contains("MyDepartment")) select usr;

或者-IEnumerable.Any在这里比Contains-查看其他答案更好

于 2012-07-23T08:42:14.767 回答