linq - How to Merge two lists and Merge it's inner lists without duplication in C# -
i'm trying merge 2 generic list using linq-
list<linkedtable> firstlink list<linkedtable> secondlink as shown in class below, generic list has generic list in it.
public class linkedtable { public string tableid { get; set; } public string tablename { get; set; } public list<link> innerlinks { get; set; } } public class link { public boolean linkflag; public string descriptor { get; set; } public string recordid { get; set; } } when merge 2 lists, new list doesn't contain both "innerlinks" records of firstlink , secondlink. have tried following code:
firstlink = firstlink.concat(secondlink) .groupby(e1 => e1.tableid) .select(e2 => e2.firstordefault()) .tolist(); now firstlink tables grouped "tableid ", few "innerlinks" secondlink missing.
i need both list of "innerlinks" firstlink , secondlink in new merged list without repetition.
example:
firstlink[0].innerlinks[0] .innerlinks[1] .innerlinks[2] secondlink[0].innerlinks[1] .innerlinks[2] .innerlinks[3] merged link should be:
firstlink[0].innerlinks[0] .innerlinks[1] .innerlinks[2] .innerlinks[3]
here's option:
first, you'll have provide way tell linq makes link equal another. can of methods:
- creating class implements
iequalitycomparer<link>, pass instance of parameterdistinct; - implementing
iequatable<link>, overridinggethashcodeon link class - overriding
equals,gethashcodeon link class.
assuming recordid unique identifier link object, how implementing iequatable<link>:
public class link : iequatable<link> { public boolean linkflag; public string descriptor { get; set; } public string recordid { get; set; } public bool equals(link other) { //adjust suiting identifier , sanity checks, if needed. return this.recordid == other.recordid; } public override int gethashcode() { //you can use gethash approach suits better. return this.recordid.gethashcode(); } } then, can concat both lists, group tableid , tablename. last, use selectmany on grouped linkedtable's innerlinks select links contained on group. distinct have take instance of iequalitycomparer in case opted go way.
var merged = item in firstlink.concat(secondlink) group item new { id = item.tableid, name = item.tablename } tbgp select new linkedtable { tableid = tbgp.key.id, tablename = tbgp.key.name, innerlinks = tbgp.selectmany(p => p.innerlinks).distinct().tolist() }; selectmany explained on documentation
distinct , iequalitycomparer<t> explained on documentation
distinct , iequatable<t> explained on msdn
overriding equals , gethashcode on msdn
Comments
Post a Comment