简体   繁体   中英

How to get common object from a list of object based on a property?

How do I combine two list based on similar properties. Let's say I have list A and List B. List A has Name property and List B has Name property. If the name of list A matches with the Name property of List B. Then save that object in a new list. How do I do this for the a number of lists that will be provided by user. So if user provides five lists. I want to get that object of all the objects whose property name matches. I can do it for two lists, using groupby but how to do it several lists?

 class Customer
{
     public int ID {get; set;}
     public string description {get; set;}
}



   List<Customer> AllCustomer; 
   var lst = new List<Hotel>();

         foreach (var item in AllCustomer)
            {


                var lst = CustomrBO.FetchSales(item);
            }

How do I get a list of Hotel's object if the HotelRegistration property of hotel matches for each customer?

               var resultSet = source.GroupBy(x => x.Name)
                   .Where(g => g.Count() > 1)
                  .SelectMany(x => x);

好吧,为什么不使用List<T>.AddRange()方法加入用户提供的所有这5个列表,并使用当前正在遵循的相同过程

void Main()
{
    IList<Customer>  AllCustomers;
    IList<Hotel>      Hotels;

    var reg = from h in Hotels
              join c in AllCustomers on h.HotelRegistration equals c.Name
              select h;


}
class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string description { get; set; }
}

class Hotel
{
    public int ID { get; set; }
    public string HotelRegistration  { get; set; }
    public string description { get; set; }
}

I resolved it in one line code:

class Program
{
    static void Main(string[] args)
    {
        var specialList = new List<C>();
        specialList.AddRange(listA.Where(x => ListB.Where(c => c.Name == x.Name).Any()).Select(x => new C()
        {
            Name = x.Name
        }));
    }
}

public class A
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

public class B
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CompanyName { get; set; }
}

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

If you use of this code, yo will have many way to create your special object. If you have question for many feature of this, comment me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM