Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two list on a specified column

Tags:

c#

list

I am attempting to join two lists (flist and slist) on the ID column. List definitions, class definitions, list contents, and desired results are displayed below.

List<first> flist= new List<first>();
List<second> slist= new List<second>();


public class first
{
   public string name { get; set; }
   public int ID{ get; set; }
   public string itemAttr { get; set; }
}
public class second
{
   public int ID{ get; set; }
   public string itemAttr{ get; set; }
}

List contents

flist:
apples | 1
bananas| 2
trees  | 3

slist:
1      | fruit
3      | not-fruit

Desired result:

flist:
apples   |   1     | fruit
bananas  |   2     |
trees    |   3     | not-fruit
like image 803
Andy Dudley Avatar asked Feb 21 '13 16:02

Andy Dudley


2 Answers

List<first> flist= new List<first>();
List<second> slist= new List<second>();

var result = from f in flist
             join s in slist on f.ID equals s.ID into g
             select new {
                 f.name,
                 f.ID,
                 itemAttr = g.Any() ? g.First().itemAttr : null
             };
like image 152
Sergey Berezovskiy Avatar answered Oct 25 '22 15:10

Sergey Berezovskiy


Try this

foreach(var f in first)
{
    foreach(var s in second)
    {
        if(f.ID == s.ID)
        {
            f.fAttr = item.itemAtrr;
        }
    }
}
like image 24
Yasser Shaikh Avatar answered Oct 25 '22 14:10

Yasser Shaikh