如何在此方案中编写Linq查询

时间:2017-10-31 12:38:02

标签: c# .net linq

只有当ObjAList中的ObjA ID1和ID2与ObjBList中的ObJB ID1和ID2匹配时,我才需要查询MainObjList并在ObjA上调用DoSomething()。

 public List<MainObj> MainObjList { get; set; }


 public class MainObj
    {
       public  List<ObjA> ObjAList { get; set; }

       public  List<ObjB> ObjBList { get; set; }

    }


    public class ObjA
    {
        public int ID1 { get; set; }
        public int ID2 { get; set; }

        public void DoSomething()
        {
            //Do something Here
        }
    }

    public class ObjB
    {
        public int ID1 { get; set; }
        public int ID2 { get; set; }
    }

5 个答案:

答案 0 :(得分:1)

我认为以下内容应该有效,尽管嵌套foreach并不理想:

foreach (MainObj mainObj in MainObjList)
{
    IEnumerable<ObjA> objAMatches = mainObj.ObjAList
        .Join(mainObj.ObjBList, 
            objA => (objA.ID1, objA.ID2), 
            objB => (objB.ID1, objB.ID2), 
            (a, b) => a);

    foreach (ObjA objA in objAMatches)
    {
        objA.DoSomething();
    }
}

答案 1 :(得分:1)

尝试加入列表并通过SelectMany将其合并到一个集合中:

MainObjList.SelectMany(x => x.ObjAList.Join(x.ObjBList,
                        a => new { a.ID1, a.ID2 },
                        b => new { b.ID1, b.ID2 },
                        (a, b) => a))
             .ToList()
             .ForEach(x => x.DoSomething());

答案 2 :(得分:0)

您可以尝试LINQ - 表达式。 您需要join两个实体并比较ID。

var mainObj = new MainObj(); //// Init your object and fill it with data

var equals = from objA in mainObj.ObjAList
        join objB in mainObj.ObjBList on new { objA.ID1, objA.ID2 } equals new { objB.ID1, objB.ID2 }
        select objA;

foreach(var entry in equals)
{
    entry.DoSomething();
}

答案 3 :(得分:0)

我不认为MainObjectList应该是一个列表。请参阅以下代码:

    public class Test
    {
        public MainObj MainObjList { get; set; }

        public Test()
        {
            var groups = from a in MainObjList.ObjAList
                         join b in MainObjList.ObjBList on a.ID1 equals b.ID1
                         where a.ID2 == b.ID2
                         select new { a = a, b = b };

        }

        public class MainObj
        {
           public  List<ObjA> ObjAList { get; set; }

           public  List<ObjB> ObjBList { get; set; }

        }


        public class ObjA
        {
            public int ID1 { get; set; }
            public int ID2 { get; set; }

            public void DoSomething()
            {
                //Do something Here
            }
        }

        public class ObjB
        {
            public int ID1 { get; set; }
            public int ID2 { get; set; }
        }
    }

答案 4 :(得分:0)

这样的东西?

MainObjList.ForEach(x =>
{
    x.ObjAList.Where(a => x.ObjBList.Any(b => b.ID1 == a.ID1 && b.ID2 == a.ID2))
              .ToList()
              .ForEach(m => m.DoSomething());
});