I have following list:
List<MyType> myList = new List<MyType>
{
new MyType {Key = "aa", Value = "test1"},
new MyType {Key = "bb", Value = "test2"},
new MyType {Key = "zz", Value = "testzz"},
new MyType {Key = "cc", Value = "test3"},
new MyType {Key = "yy", Value = "testyy"},
new MyType {Key = "dd", Value = "test4"},
new MyType {Key = "ee", Value = "test5"}
};
where,
public class MyType
{
public string Key { get; set; }
public string Value { get; set; }
}
Now, I would like to retrieve all the objects within the range based on the value of Key. That is, I would like to select all the objects from the list starting from the Key="bb" to Key="dd" (no alphabetic ordering) so that I would have the following result:
new MyType {Key = "bb", Value = "test2"},
new MyType {Key = "zz", Value = "testzz"},
new MyType {Key = "cc", Value = "test3"},
new MyType {Key = "yy", Value = "testyy"},
new MyType {Key = "dd", Value = "test4"}
How can I achieve this using linq/lambda expression?
[Update: 12/30/2015]: The key are NOT ordered alphabetically and there might be hundreds of keys. So, solutions involving list.Contains(..) and assuming alphabetic ordering will not work. I have also updated the example to include objects with keys 'yy' and 'zz' to reflect the same.
If you have a disjoint set of keys then you can use the Contains operator:
var keys = new [] { "bb", "cc", "dd" };
var result = myList.Where(x => keys.Contains(x.Key));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With