1

I have 2 lists of string and I am merging them but selecting a specific column. I managed to get it, but I am sure there is a better way:

public List<string> GetAll()
{
    var i = _iRepository.GetAll().Select(x => x.Name).ToList();
    var a = _aRepository.GetAll().Select(x => x.Name);
    i.AddRange(a);
    return i;
}

3 Answers3

3
List<string> allNameList = _iRepository.GetAll()
    .Select(x => x.Name)
    .Concat(_aRepository.GetAll().Select(x => x.Name))
    .ToList();

If you want to remove duplicates use Union instead of Concat.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

Pull the string out of list one, and concatenate it to the list of string from list 2:

 _iRepository.Select(x => x.Name).Concat(_aRepository.Select(x => x.Name)).ToList()

ps; I'm not sure how you have 2 lists of string - if _iRepository were a list of string, you wouldn't be able to select x.Name because a string doesn't have a .Name property! The lists are List<SomeObjectThatHasANameProperty>, surely.. ?

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

Shorter (assuming both GetAll() return the same type) :

return _iRepository.GetAll().Concat(_aRepository.GetAll()).Select(x => x.Name).ToList();

A bit more efficient (less memory allocations) if GetAll() returns a new list:

var list = _iRepository.GetAll();
list.AddRange(_aRepository.GetAll());
return list.ConvertAll(x => x.Name);
Slai
  • 22,144
  • 5
  • 45
  • 53