-1

这是我的课,

public class App
{
   public string Appname;
   public string Appcode;

}

我有一个应用程序列表,例如

List<App> apps;

另一个相同对象的列表,例如

List<App> filteredapps;

现在我需要从第二个列表中具有相同应用程序名称的第一个列表中进行过滤。我怎样才能做到这一点

4

3 回答 3

1

你需要使用 Enumerable.Intersect 方法:http: //msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx

void Main()
{
    List<App> apps;
    List<App> filteredapps;

    var query=apps.Intersect(filteredapps,new AppComparer());


}
public class App
{
   public string Appname;
   public string Appcode;

}

class AppComparer : IEqualityComparer<App>
{

    public bool Equals(App x, App y)
    {

    if (Object.ReferenceEquals(x, y)) return true;


    if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
        return false;


    return x.Appname == y.Appname && x.Appcode == y.Appcode;
}

// If Equals() returns true for a pair of objects  
// then GetHashCode() must return the same value for these objects. 

public int GetHashCode(App product)
{
    //Check whether the object is null 
    if (Object.ReferenceEquals(App, null)) return 0;

    //Get hash code for the Name field if it is not null. 
    int hashProductName = product.Appname == null ? 0 : product.Appname.GetHashCode();

    //Get hash code for the Code field. 
    int hashProductCode = product.Appcode.GetHashCode();

    //Calculate the hash code for the product. 
    return hashProductName ^ hashProductCode;
}

}
于 2013-09-06T09:22:59.400 回答
0
apps.where(a=>filteredApps.Select(fa=>fa.AppName).Contains(a.AppName))

或者

var filteredNames = filteredApps.Select(fa=>fa.AppName);
apps.where(a=>filteredNames.Contains(a.AppName))
于 2013-09-06T09:15:53.790 回答
0
var query = apps.Where(x=>filteredapps.Any(y=>y.AppName == x.AppName));

如果您想要 aList而不是a ,请在查询末尾IEnumerable添加。.ToList()

于 2013-09-06T09:17:17.880 回答