Subtract a generic list from another

前端 未结 6 809
天涯浪人
天涯浪人 2020-12-13 23:02

I am trying remove a list of firmIDs from one list from another. I don\'t really understand linq but I am pretty sure I need to use it.

List firm         


        
相关标签:
6条回答
  • 2020-12-13 23:34

    The best approach would be Except() for you case. However, if the List object is different then other one, you can use All()

    firms.Where(x=> trackedFirms.All(y => y.FirmId != x.FirmId)
    
    0 讨论(0)
  • 2020-12-13 23:39

    If you have list X and a list Y, and you want to remove all items in Y that are in X you can experiment with the following:

    X.Intersect(Y)

    Comparing two Lists and returning the distinct values and the differences

    0 讨论(0)
  • 2020-12-13 23:48

    From your code above, I presume you are trying to get entries from Firms that have a corresponding item in TrackedFirms.

    List<Firm> results = Firms.Where(f => TrackedFirms.Any(t => t.FirmId == f.FirmId)).ToList();
    

    If on the other hand you want untracked firms, then it's :

    List<Firm> results = Firms.Where(f => !TrackedFirms.Any(t => t.FirmId == f.FirmId)).ToList();
    
    0 讨论(0)
  • 2020-12-13 23:49
    var result = firms.Except(trackedFirms); // returns all the firms except those in trackedFirms
    
    0 讨论(0)
  • 2020-12-13 23:52

    Contains is the native method of List<T> that expects you to pass in a T. You want Where instead.

    var result = firms.Where(i => trackedFirms.Contains(i.FirmID));
    

    If you expect result to be a List<T> then add .ToList() to the end of your Where LINQ expression.

    0 讨论(0)
  • 2020-12-13 23:56

    I think this should works

    var result = firms.Where(x => !trackedFirms.Any(y => x.FirmID == y.FirmID));
    

    From all the firm in firms select the firm that isn't in the trackedFirms (at least this is what i understand from your question).

    0 讨论(0)
提交回复
热议问题