假设我有一个具有以下结构的表:
- Id
- Phone1
- Phone2
- Address
此表有多条记录。 使用linq to SQL,在每行中选择所有电话号码(来自列#34; Phone1"和#34; Phone2")以及删除重复值的最佳方法是什么?
我尝试了类似但我每行只能获得一列(Phone1):
var listOfResults = (from x in table
select x.Select(z => z.Phone1).Distinct()
).ToList();
非常感谢!
答案 0 :(得分:1)
你可以这样做:
var listOfResults = (from x in table
select new
{
Phone1 = x.Phone1,
Phone2 = x.Phone2
}).Distinct();
或使用groupby:
var listOfResults = (from x in table
group x by new { x.Phone1,x.Phone2 } into g
select new
{
Phone1 = g.Key.Phone1,
Phone2 = g.Key.Phone2
});
var listOfResults = (from x in table
select new[]
{
new { Phone = x.Phone1 },
new { Phone = x.Phone2}
}).SelectMany(x=>x).Distinct();
答案 1 :(得分:0)
var listOfPhone1 = (from x in table select x.Select(z => z.Phone1);
var listOfPhone2 = (from x in table select x.Select(z => z.Phone2);
var listOfResults = (listOfPhone1.AddRange(listOfPhone2)).Distinct();
答案 2 :(得分:0)
您可以查看此处找到的MoreLinq库。他们有一个名为 DistinctBy 的功能,可以解决您的问题。
答案 3 :(得分:0)
我不知道这是否适用于Linq-to-SQL,但是使用Linq-to-Object我会这样做:
var unified = addresses.SelectMany(Row => new[] { new { Row, Phone = Row.Phone1 }, new { Row, Phone = Row.Phone2 } })
.Distinct(entry => entry.Phone)
.Select(entry => entry.Row);