1

我已经编写了以下 linq 查询,但没有得到预期的结果。例如,我的预期结果是 lst 和 list 之间的所有匹配记录以及 list 中的所有不匹配记录。

我想要以下结果

a,b,c,d,e,f

public class Com : IEqualityComparer<DuplicateData>
    {
        public bool Equals(DuplicateData x, DuplicateData y)
        {
            return x.address.Equals(y.address);
        }

        public int GetHashCode(DuplicateData obj)
        {
            return obj.address.GetHashCode();

        }
    }

static void Run ()
{
    List<string> lst = new List<string>();
    lst.Add("a");
    lst.Add("b");
    lst.Add("c");
    lst.Add("p");

    List<DuplicateData> list = new List<DuplicateData>()
    {
        new DuplicateData{address="a"},
        new DuplicateData{address="a"},
        new DuplicateData{address="a"},
        new DuplicateData{address="b"},
        new DuplicateData{address="b"},
        new DuplicateData{address="c"},
        new DuplicateData{address="d"},
        new DuplicateData{address="e"},
        new DuplicateData{address="f"},
    };

    var dup = list.Distinct(new Com());
    var RightJoin = from x in dup
                    join y in lst
                    on x.address equals y
                    into right
                    from z in right
                    select new
                    {
                        UniqueAddress = z,

                    };

}
4

2 回答 2

2

试试这样:

var RightJoin = from x in dup
                join y in lst
                on x.address equals y
                into right
                from z in right.DefaultIfEmpty(x.address)
                select new
                {
                    UniqueAddress = z,
                };

结果是 (a,b,c,d,e,f)

工作样本:http: //ideone.com/MOIhZH


解释

要在 linq 中进行左/右连接,您必须使用DefaultIfEmpty方法,当没有匹配项(连接结果为空)时,将产生(默认)结果。但是,字符串的默认值是null,因此您必须从“左侧”集合中提供默认值才能在结果集中看到它。


替代方法

这可能是更方便的方法。您不会选择 fromz并提供默认值,而是选择 from x.address- 连接的左侧。

var RightJoin = from x in dup
                join y in lst
                on x.address equals y
                into right
                from z in right.DefaultIfEmpty()
                select new
                {
                    UniqueAddress = x.address,
                };
于 2013-07-09T10:29:16.170 回答
0

这应该有效:

var res = from x in list
          join y in lst on x.address equals y into right 
          from xy in right.DefaultIfEmpty()
          select new { UniqueAddress = xy };

结果:

{ UniqueAddress = a },
{ UniqueAddress = a },
{ UniqueAddress = a },
{ UniqueAddress = b },
{ UniqueAddress = b },
{ UniqueAddress = c },
{ UniqueAddress = null },
{ UniqueAddress = null },
{ UniqueAddress = null }
于 2013-07-09T10:07:18.297 回答