0

Consider this scenario

I have a class called User which contains the a List of Car types (e.g Toyota, BMW)

So that is a User can have many cars.

Let's say I have a List of type User. In this current format, I can easily find all the Cars that a User owns.

What I cannot easily do, is find the all Users who own a particular Car type (e.g all Users who own a Toyota).

In the classical database sense I want to be able to pivot the data, but how does one achieve such an operation when working with objects like this in C#?

Thanks Thomas

4

3 回答 3

4

你有一个一对多的关系,所以你可以双向。有车有车,有车有车。请参阅以下 C# 代码:

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

    public List<Car> Cars { get; set; }
}

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

var users = new List<Users>
                    {
                        new Users
                            {
                                Name = "Bob",
                                Cars = new List<Car> { new Car { Name = "Toyota" } }
                            }
                    };

// Any Cars with Name "Toyota" in a User's list of cars.    
var usersWithCar = users.Where(user => user.Cars.Any(car => car.Name == "Toyota"));


string userName = usersWithCar.Single().Name; // Bob
于 2013-04-18T15:36:14.717 回答
0

您可以使用 LINQ 来实现这一点。

    class Car {}
    class Toyota : Car {}
    class BMW : Car {}

    class User
    {
        private readonly IList<Car> cars = new List<Car>();
        public IList<Car> Cars { get { return cars; } }
        public void AddCar(Car car)
        {
            Cars.Add(car);
        }
    }


    User user1 = new User();
    user1.AddCar(new BMW());
    user1.AddCar(new Toyota());

    User user2 = new User();
    user2.AddCar(new BMW());

    var users = new List<User>
                        {
                            user1,
                            user2
                        };
    IEnumberable<User> usersWithBMW = users.Where(u => u.Cars.Any(c => c is BMW));
于 2013-04-18T15:46:26.997 回答
0

您应该尝试使用 Linq,首先您需要添加对 System.Linq 的引用(如果尚未完成)

接下来,您可以执行以下操作:

List<User> Example = new List<User>();
var Users_Having_A_Renault_ZE = Example.Where(
Me => Me.MyCars.Any(
    Car => Car.MyName == "Renault ZE"))

这意味着“接受所有拥有一辆或多辆名为 Renault ZE 的汽车的用户”+ 它假设 MyCars 是一个列表、一个数组或类似的东西。

于 2013-04-18T15:44:11.927 回答