简体   繁体   中英

Filtering a list and removing unwanted data C#

I have a list of users for a timespan , for arguments sake let's say a month. So in that list certain users do not meet the criteria I want for a certain objective so I want to filter out the list and display the filtered out data into another list . So how I replicated the list was as follows:

List<tblList1> List1 = new XPQuery<tblList1>(session)
    .Where(w => w.UserCode != null).ToList();

I then use a foreach loop to go through this list to compare the data to my criteria and then add them to the new list which is working perfectly. The problem I now have is to delete the data I took from the first list . I tried the following in a new method which I created:

public void DeleteData(Session session)
{
    List<tblList1> List1= new XPQuery<tblList1>(session)
        .Where(w => w.UserID != null).ToList();

    List<tblList2> List2= new XPQuery<tblList2>(session)
        .Where(w => w.UserID!= null).ToList();

    List1.RemoveAll(w => w.UserID == List2.Any(e => e.UserID== w.UserID));
}

So in the end I want to remove all the data in list1 so that we can view the deleted data in list2. Any help would be appreciated if I can just get the RemoveAll LINQ statement correct as the current line does not work and I am unsure of how to handle this in LINQ.

As far as I can see from comments:

I want to take List1 {1, 2, 3} compare them to criteria and see that { 2 } does not meet that criteria and add that in List2. Then delete { 2 } from List1

I can't see any need in Linq at all. Let's fill both Lists in parallel:

List<tblList1> List1 = new List<tblList1>();
//TODO: please, check types; it seems that it should be List<tblList1> List2
List<tblList2> List2 = new List<tblList2>();

foreach (var item in new XPQuery<tblList1>(session).Where(w => w.UserID != null)) {
  if (YourCriteriaHere)
    List1.Add(item); // <- Criteria met: add to List1 
  else
    List2.Add(item); // <- Doesn't meet: "delete" from (just not add to) List1 into List2 
}

You can just use LINQ Where to filter your list, and then Except to get unfiltered values:

List<Item> all = ...; // your original list
List<Item> matching = all.Where(x => IsMatching(x)).ToList(); // IsMatching is any filtering logic
List<Item> notMatching = all.Except(matching).ToList();

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