Compare the elements of two different types of C # lists

I want to compare two different lists with one common property (Name). I tried things like the .Contains () method, but this does not work because I am dealing with lists of two different objects. I tried solutions in issues such as:

C # Comparing two lists of different objects

C #, compare two different types of lists

compare different types of lists in c #

But these solutions do not work because my lists expect a Property or Animal object, not a "string", that's where I got stuck.

I have two classes:

 public class Animal
    {
        public string Name = string.Empty;
        public string XChromosome = string.Empty;
        public string YChromosome = string.Empty;
    }

public class Properties
{
    public string Name = string.Empty;
    public string Prop1 = string.Empty;
    public string Prop2 = string.Empty;
}

The two lists are as follows:

List<Animal> = "name", "xposition", "yposition"
               "name1", "xposition1", "yposition1" etc..

List<Properties> = "name", "prop1","prop2"
                   "name1", "prop3", "prop4" etc..  

What I would like to do is compare the two lists and, if the match is "Name", I would like to get the contents of both lists belonging to this name. I also tried using a HashSet or dictionary, but that is not what I am looking for.

+4
2

Name :

from a in animals
join p in properties on a.Name equals p.Name
select new {
   a.Name,
   a.XChromosome,
   a.YChromosome,
   p.Prop1,
   p.Prop2
}

.NET Fiddle.


. , , , ( ):

  from a in animals
  join p in properties on a.Name equals p.Name into g
  from p in g.DefaultIfEmpty()
  select new {
     a.Name,
     a.XChromosome,
     a.YChromosome,
     Prop1 = p?.Prop1,
     Prop2 = p?.Prop2
  }

- , . , Prop1 Prop2 ( ).

+8

, upvotes , . class Named, :

class Named {
    public string Name = string.Empty;
}

class es , :

 public class Animal : Named
    {
        public string XChromosome = string.Empty;
        public string YChromosome = string.Empty;
    }

public class Properties : Named
{
    public string Prop1 = string.Empty;
    public string Prop2 = string.Empty;
}

List<Named> , LINQ, . , class es, , - / , .

+1

Source: https://habr.com/ru/post/1671572/


All Articles