Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,

I need to find distinct namesfrom a list and it should return List<Contribution>

Below is my list
C#
 List<LinearGrowth> lstlg = new List<LinearGrowth>()
{ new LinearGrowth {year=2016,endingvalue=23.5, cahflow=new List<Contribution>()
 {new Contribution{id=1,name="Salary"},
   new Contribution{id=2,name="Rent"},
   }},                                                                
 new LinearGrowth{year=2017,endingvalue=25.0,cahflow=new List<Contribution>()
 {new Contribution{id=1,name="Salary"},
   new Contribution{id=2,name="Rent"},
   new Contribution{id=3,name="interest"},
   }},
 new LinearGrowth{year=2018,endingvalue=29,cahflow=new List<Contribution>()
  {new Contribution{id=1,name="Salary"},
   new Contribution{id=2,name="Rent"},
   new Contribution{id=4,name="FD"},
   new Contribution{id=5,name="MutualFund"},
   }},
};


Result Should be
1 salary
2 Rent
3 Interest
4 FD
5 Mutual Fund

Please help

What I have tried:

var res = lstlg.SelectMany(cf => cf.cahflow)
.Select(d => new Contribution { id = d.id, name = d.name, })
.Distinct();
Posted
Updated 13-Mar-16 7:23am

1 solution

Create your own comparison class

C#
public class MyComp : IEqualityComparer<Contribution>
{
    public bool Equals(Contribution x, Contribution y)
    {
        return (x.id == y.id);
    }

    public int GetHashCode(Contribution obj)
    {
        return obj.id.GetHashCode();
    }
}


Then use;

C#
List<Contribution> results = lstlg.SelectMany(l => l.cahflow).Distinct(new MyComp()).ToList();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900