从每行中选择多列并删除重复项

Selecting multiple columns from each row and removing duplicates

假设我有一个具有以下结构的 table:

- Id
- Phone1
- Phone2
- Address

这个table有多个记录。 最好的方法是什么,使用 linq to SQL,选择每一行中的所有 phone 数字(来自 "Phone1" 和 "Phone2" 列),并删除重复的值。

我试过类似的方法,但我只能在每一行中得到一列 (Phone1):

var listOfResults = (from x in table
                     select x.Select(z => z.Phone1).Distinct() 
                     ).ToList();

非常感谢!

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();

您可以查看此处的 MoreLinq 库。他们有一个名为 DistinctBy 的函数,应该可以解决您的问题。

你可以这样做:

 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();

我不知道这是否适用于 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);