简体   繁体   中英

foreach first list and see if it exists in the 2nd list and if it does then get other values from 2nd list

foreach first list by using ID and ID_SCH and see if it exists in the 2nd list and if it does then get other values from 2nd list.

string getRecords = "SELECT .....";
         List <Records> firstList = ReadAll(getRecords, reader => {
           return new Records(
             reader.ReadByName(NameRecord.ID, string.Empty),
             reader.ReadByName(NameRecord.ID_SCH, string.Empty)
           );
         });

         string getAllRecords = "SELECT .....";

         List <Records> secondList = ReadAll(getAllRecords, reader => {
           return new Records(
             reader.ReadByName(NameRecord.ID, string.Empty),
             reader.ReadByName(NameRecord.ID_SCH, string.Empty),
             reader.ReadByName(NameRecord.BSID, string.Empty),
             reader.ReadByName(NameRecord.BSID_SCH, string.Empty),
           );
         });

// currently I am able to use id only. But I would like to include `id` and `id_sch` as well in the below statement and then get the value of `BSID` and `BSID_SCH`.

var aa= data.Select(l1 => l1.Id).Intersect(secondList .Select(l2 => l2.Id)).ToList();

Acceptance criteria

1.foreach test in the first list see if it exists in the 2nd list. some how I managed to use id to get the result but I would like to use id_sch` as well.

  1. if it does, get the tests that are excluded from 2nd list like BSID and BSID_SCH

  2. after getting the BSID and BSID_SCH value from acceptance criteria 2, need to check if these BSID and BSID_SCH value exist in firstlist

  3. If it exists in the first list then how to get the value of id idsch from first list.

You can use tuples to combine the two values. In a first step we add the values of the first list into a HashSet<T> , so that we can test whether an item exists fast and easily.

var l1Exclude = data
    .Select(l1 => (l1.Id, l1.id_sch))
    .ToHashSet();
var l1Include = data
    .Select(l1 => (l1.BSID, l1.BSID_SCH))
    .ToHashSet();

Now, you can use this result to filter the second list with of all its properties

IEnumerable<Records> result = secondList
    .Where(l2 => l1Include.Contains((l2.BSID, l2.BSID_SCH)) &&
                 !l1Exclude.Contains((l2.Id, l2.id_sch)));

But a fundamental question is, whether it would not be easier and faster to perform this logic in SQL directly yielding the expected result. Something like this

SELECT b.*
FROM
    Table2 b
    INNER JOIN Table1 a
        ON b.BSID = a.BSID AND b.BSID_SCH = a.BSID_SCH
WHERE
    NOT EXISTS (SELECT *
                FROM Table1 aa
                WHERE aa.Id = b.Id AND aa.IdSch = b.IdSch)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM