Linq - 用find查找

时间:2013-01-17 13:25:09

标签: linq join lambda

我是linq的全新人,需要帮助。 这些是我的poco课程:

public class User {
   public User()
   {
      this.Profiles = new List<Profile>();
   }

   public Guid ID { get; set; }        
   public bool IsValid{ get; set; }       
   public virtual ICollection<Profile> Profiles { get; set; }
}

public class Profile {
   public Profile() {
      this.Users = new List<User>();
      this.Customers = new List<Customer>();
   }

   public Guid ID { get; set; }
   public string Name { get; set; } 
   public virtual ICollection<User> Users { get; set; }
   public virtual ICollection<Customer> Customers { get; set; }
}

public class Customer {
   public Customer()
   {
      this.Profiles = new List<Profile>();
   }

 public Guid ID { get; set; }
 public string Number { get; set; }       
 public virtual ICollection<Profile> Profiles { get; set; }
}

我想搜索有特殊客户的有效用户。特殊客户来自其他用户。所以我会发送另一个用户作为方法参数。

是否可以使用linq或我需要存储过程来解决问题?

祝你好运

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

public static List<User> FindAllUsersBySameCustomers(User sourceuser)
{
    var res = sourceuser.Profiles.SelectMany(p => p.Customers)
                                 .SelectMany(c => c.Profiles)
                                 .SelectMany(p => p.Users)
                                 .Distinct();
    return res.ToList();
}

但要注意,只有在我的示例here中填充(包含)您的关系时,它才会起作用。

你不应该在构造函数中调用虚拟成员。 Anwer就在这里:Virtual member call in a constructor

答案 1 :(得分:0)

试试这个..

/// <summary>
    /// Search for valid Users with special customers. 
    /// Special customers would come from another user. 
    /// So I would send another user as method argument.
    /// </summary>
    /// <returns></returns>
    public List<User> FindValidUsersWithSpecialCustomers(List<User> allUsers, User anotherUser)
    {   
        var specialCustomers = anotherUser.Profiles.SelectMany(aProfile => aProfile.Customers);//.Select(cust => cust.Number == "SpecialCustomerNumber" && cust.ID == new Guid("SpecialCustomerGuid"));

        Func<IEnumerable<Customer>, IEnumerable<Customer>, Boolean> IsSpecialCustomersPresentInThisCustomersList =
            delegate(IEnumerable<Customer> customerList, IEnumerable<Customer> specialCustomersList)
            {
                if ((from cust in customerList where specialCustomersList.Contains(cust) select cust).Any())
                    return true;
                else
                    return false;
            };

        var validUsersWithSpecialCustomers = (from user in allUsers where user.IsValid && IsSpecialCustomersPresentInThisCustomersList(user.Profiles.SelectMany(p => p.Customers), specialCustomers) select user);

        return validUsersWithSpecialCustomers.ToList();
    }