I have list of objects and I have list of strings.
List<String> states = new List<String>();
states.add("wisconsin");
states.add("Florida");
states.add("new york");
List<Foo> foo = new List<Foo>();
foo.add(new Foo(2000, name1, "wisconsin"));
foo.add(new Foo(1000, name2, "california"));
foo.add(new Foo(300, name3, "Florida"));
An object have three properties: int age, string name and string state.
and I have added these objects to the list. Second list consists of string of "states".
How I can compare these two lists? What is best way to do it? I want to know if one of objects have same "state", which other list consist. Please guide me.
It sounds like you want something like:
List<Person> people = ...;
List<string> states = ...;
var peopleWithKnownStates = people.Where(p => states.Contains(p.State));
Or just to find if any of the people have known states:
var anyPersonHasKnownState = people.Any(p => states.Contains(p.State));
Both of these use LINQ - if you haven't come across it before, you should definitely look into it. It's wonderfully useful.
You might want to change your states
to a HashSet<string>
so that the Contains
operation is quicker though.
See more on this question at Stackoverflow