How can I convert the below loop into simple linq code. The program is filtering out duplicate records.You can see the combination of SyID and PtID is repeating in the list, Those records should have only one entry in filtered list.First we need group the items by SyID then get distinct PtID from the list.
public class ConnectionDetail
{
public long SyID { get; set; }
public long PtID { get; set; }
public double Usage { get; set; }
}
class Program
{
static void Main(string[] args)
{
var details = new List<ConnectionDetail>();
details.Add(new ConnectionDetail() { SyID = 1, PtID = 1, Usage = 1500 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 1, Usage = 1500 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 2, Usage = 560 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 3, Usage = 850 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 4, Usage = 1222 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 5, Usage = 2000 });
details.Add(new ConnectionDetail() { SyID = 1, PtID = 5, Usage = 2000 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 1, Usage = 1500 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 2, Usage = 1300 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 3, Usage = 560 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 3, Usage = 560 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 4, Usage = 1580 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 4, Usage = 1580 });
details.Add(new ConnectionDetail() { SyID = 2, PtID = 5, Usage = 4000 });
var distinctSet = new List<ConnectionDetail>();
foreach (var detail in details)
{
if (!distinctSet.Any(x => x.SyID == detail.SyID && x.PtID == detail.PtID))
{
distinctSet.Add(new ConnectionDetail() { SyID = detail.SyID, PtID = detail.PtID, Usage = detail.Usage });
}
}
Console.ReadKey();
}