简体   繁体   中英

How to build List by using data from another List using LINQ

i have some List that hold 1 or more Guid.

var getMyfirstListGuids = (from dlist in db.MyTable
    where dlist.id == theid
    select dlist).ToList();

List<MyfirstList> myfirstList = new List<MyfirstList>();

foreach (var item in myLandingPageList)
{
    Guid theguid = new Guid(item.guid);
    MyfirstList addnewRow = new MyfirstList();
    addnewRow.LpGuid = new Guid(theguid);
    myfirstList.Add(addnewRow);
} 

Now i have a list with 1 or more guids. my next step is to make list with data from SQL by the first list guids. In the SQL could be 1 row or more for each guid. with one row result i can guess what to do. but if there is many results i dont have an idea.

Okay so you wanna do it like this:

List<SecondListGUID> secondListGUID = new List<SecondListGUID>();
foreach (var item in myfirstList)
{
    for(int i = 0; i<_yourDBEntity.GUIDs.Count(); i++)
    {
        if(item.LpGuid == _yourDBEntity.GUIDs[i].GUID)
        secondListGUID.add(
            new SecondListGUID() {
                // add the corresponding GUID's here 
        });
    }
}

Basically you have to do a foreach through your first List and then do a for loop (or foreach - whichever you prefer) through your DB table (entity in this case if you're using Entity framework) and simply compare the GUID's from your DB table and if they match you'll wanna add the item to your third list.

PS I've worked with the informations that you've provided, you can change the 2nd list type into the one you need, and change your entity framwork data model name into the one you actually use :)

You can try this

List<Guid>getMyfirstListGuids =  new List<Guid>();

getMyfirstListGuids.addRange(from dlist in db.MyTable
    where dlist.id == theid
    select dlist).ToList());

List<MySecList> mySecList = new List<MySecList>();

mySecList.AddRange(_db.myLandingPageList.Where(p => p.Guid.Any(x => getMyfirstListGuids.Contains(x));

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