首页 新闻 搜索 专区 学院

List<T>重复项合并

0
[已解决问题] 解决于 2010-12-01 09:06
<table border="0px" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="table_main_title" align="center">&nbsp;<span>2010-11-30 &nbsp; &nbsp;&nbsp;</span></td> <td align="center">这是内容1</td> </tr> <tr> <td class="table_main_title" align="center"><span>2010-11-30 &nbsp; &nbsp;</span></td> <td align="center">这是内容2<br /></td> </tr> <tr> <td class="table_main_title" align="center">&nbsp;<span>2010-11-30 &nbsp; &nbsp;&nbsp;</span></td> <td align="center">这是内容3<br /></td> </tr> <tr> <td class="table_main_title" align="center">&nbsp;<span>2010-11-29 &nbsp; &nbsp;&nbsp;</span></td> <td align="center">这是内容4<br /></td> </tr> <tr> <td class="table_main_title" align="center">&nbsp;<span>2010-11-29 &nbsp; &nbsp;&nbsp;</span></td> <td align="center">这是内容5</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>这是从List&lt;T&gt;读取出来的数据,我现在想要的效果是:</p> <table border="0px" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="table_main_title" align="center">&nbsp;<span>2010-11-30 &nbsp; &nbsp;&nbsp;</span></td> <td align="center">这是内容1,这是内容2,这是内容3</td> </tr> <tr> <td class="table_main_title" align="center"><span>&nbsp;2010-11-29 &nbsp; &nbsp;&nbsp;</span></td> <td align="center"><br />这是内容5,这是内容5<br /><br /></td> </tr> </tbody> </table> <p>&nbsp;就是说如果前面时间相等的话,把内容合并到一起?</p> <p>请教了。</p>
CHild.的主页 CHild. | 初学一级 | 园豆:4
提问于:2010-11-30 22:46
< >
分享
最佳答案
1

class Program
{
static void Main(string[] args)
{
List
<Test> tList = new List<Test>();
tList.Add(
new Test(){
time
=DateTime.Parse("2010-11-30"),
content
="这是内容1"
});
tList.Add(
new Test()
{
time
= DateTime.Parse("2010-11-30"),
content
= "这是内容2"
});
tList.Add(
new Test()
{
time
= DateTime.Parse("2010-11-30"),
content
= "这是内容3"
});
tList.Add(
new Test()
{
time
= DateTime.Parse("2010-11-29"),
content
= "这是内容4"
});
tList.Add(
new Test()
{
time
= DateTime.Parse("2010-11-29"),
content
= "这是内容5"
});



List
<Test> temp = tList.Distinct(new Comparer()).ToList<Test>();
foreach (var o in temp)
{
foreach (var p in tList)
{
if (p.time == o.time&&p.content!=o.content)
{
o.content
+= ","+p.content;
}
}
}

foreach (var o in temp)
{
Console.WriteLine(o.time
+" "+o.content);
}


Console.Read();
}
}

public class Comparer : IEqualityComparer<Test>
{
#region IEqualityComparer<Test> Members

public bool Equals(Test x, Test y)
{
if (x == null || y == null)
return false;
return x.time == y.time;
}

public int GetHashCode(Test obj)
{
return obj.ToString().GetHashCode();
}

#endregion
}

public class Test
{
public DateTime time { get; set; }

public string content { get; set; }
}

artwl | 专家六级 |园豆:16536 | 2010-12-01 07:36
受教了,问题解决了。谢谢。有时间能帮我解释下这段代码不,加点注释也行。谢谢了。
CHild. | 园豆:4 (初学一级) | 2010-12-01 09:05
就是泛型的Distinct方法的运用
artwl | 园豆:16536 (专家六级) | 2010-12-01 09:08
其他回答(2)
0

Contains()
union它有一个功能是可以去除重复项的

曾祥展 | 园豆:138 (初学一级) | 2010-11-30 23:38
0

mark

lovejean | 园豆:186 (初学一级) | 2015-12-13 13:40
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册