0

I have an object like this -

public MyObject
{
    public int Id { get; set; } 
    public string MyType { get; set; }
}

a list of those objects -

public List<MyObject> MyObjectList { get; set; }

and a list of string like this -

public List<string> MyTypeList { get; set; }

Using LINQ on MyObjectList, I want to create a list of MyObject removing any MyObject that has a MyObject.MyType that is in the MyTypeList.

Something like this (here are some unsuccessful attempts) -

List<MyObject> MyObjectListNEW = MyObjectList.Select(i => i.MyType).Except(MyTypeList).ToList();
List<MyObject> MyObjectListNEW = MyObjectList.Where(i => i.MyType.Except(MyTypeList));
1
  • 1
    List<MyObject> MyObjectListNEW = MyObjectList.Where(i => !MyTypeList.Any( t => t == i.MyType)).ToList(); Commented Oct 19, 2021 at 15:59

3 Answers 3

1

This should work:

var MyObjectList = new List<MyObject>();
var MyTypeList = new List<string>();
var results = MyObjectList.Where(m => !MyTypeList.Any(t => m.MyType == t)).ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of .Any(t => expr == t) it is often better to write .Contains(expr). The latter can go to an ordinary instance method if this is used directly on an ICollection<> or similar (which is the case in the current question), or can go to Linq's extension method Contains<TSource> in situations where we have nothing better than an IEnumerable<> as source.
0

I think it should be

var results = MyObjectList.Where(m => ! MyTypeList.Contains(m.MyType)).ToList();

Comments

0

try this

var results = MyObjectList.Where(m =>  !MyTypeList.Contains(m.MyType)).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.