0

I have a list of objects like this:

public static List<CategorySource> categorySource;
public static List<CategorySource2> categorySource2;

public class CategorySource
{
    [PrimaryKey]
    public int Id { get; set; }
    public int GroupId { get; set; }
    public string Name { get; set; }
    public int SortOrder { get; set; }
}

public class CategorySource2
{
    [PrimaryKey]
    public int Id { get; set; }
    public int GroupId { get; set; }
    public string Name { get; set; }
}

Is there a way that I can populate the categorySource2 list from the categorySource list and ignore the SortOrder property without doing a Linq select and specifying each column.

Note these are just examples as the list I have that I need to populate has over 40 properties.

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 1
    Does `CategorySource` has all `CategorySource2` fields? in that case you can use inheritance. – Guy Oct 06 '19 at 10:29
  • Is your objective only to avoid writing the mapping code? If that's the case I would give https://automapper.org a try – mariosangiorgio Oct 06 '19 at 13:57

1 Answers1

1

You can try this using inheritance as proposed by @Guy:

static void Test()
{
  categorySource.Add(new CategorySource { Id = 1, Name = "Test 1" });
  categorySource.Add(new CategorySource { Id = 2, Name = "Test 2" });
  categorySource.Add(new CategorySource { Id = 3, Name = "Test 3" });
  categorySource.Add(new CategorySource { Id = 4, Name = "Test 4" });

  categorySource2.AddRange(categorySource);

  foreach ( var item in categorySource2 )
    Console.WriteLine($"{item.Id}: {item.Name}");
}

public static List<CategorySource> categorySource = new List<CategorySource>();
public static List<CategorySource2> categorySource2 = new List<CategorySource2>();

public class CategorySource2
{
  public int Id { get; set; }
  public int GroupId { get; set; }
  public string Name { get; set; }
}

public class CategorySource : CategorySource2
{
  public int SortOrder { get; set; }
}

Since CategorySource is type of CategorySource2, you can add categorySource items in the categorySource2 list.

Doing this is called polymorphism.

What is polymorphism, what is it for, and how is it used?

Doing this you can manipulate items while ignoring SortOrder.