2

我对 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 或者我需要存储过程来解决问题?

最好的祝福

4

2 回答 2

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();
}

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

笔记

您不应该在构造函数中调用虚拟成员。Anwer 在这里:构造函数中的虚拟成员调用

于 2013-01-17T22:09:25.127 回答
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();
    }
于 2013-01-18T06:26:33.077 回答