11,567 questions
Try this approach:
string start = "2010 FYA";
string end = "3Q 2014A";
bool f = true;
var result = periods.SkipWhile( p => p != start ).TakeWhile( p => { bool b = f; f = p != end; return b; } );
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
List<string> periods = new List<string>();
periods.Add("2010 FYA");
periods.Add("2011 FYA");
periods.Add("2012 FYA");
periods.Add("2013 FYA");
periods.Add("1Q 2014A");
periods.Add("2Q 2014A");
periods.Add("3Q 2014A");
periods.Add("4Q 2014A");
periods.Add("2014 FYA");
var xx = periods.Where(a => a.ToString() == "2010 FYA" && a.ToString() == "3Q 2014A").ToList();
IN LINQ there is no any between operator. so tell me how to use LINQ to extract data between two period.
i need to extract all data from period 2010 FYA to 3Q 2014A using LINQ. please show me how to achieve with LINQ. thanks
Try this approach:
string start = "2010 FYA";
string end = "3Q 2014A";
bool f = true;
var result = periods.SkipWhile( p => p != start ).TakeWhile( p => { bool b = f; f = p != end; return b; } );
An alternate is to use a language extension method, in this case if either item does not exists null is returned else a list is returned.
Caveats
My Between
public static bool Between<T>(this T value, T lowerValue, T upperValue) where T : struct, IComparable<T> =>
Comparer<T>.Default.Compare(value, lowerValue) >= 0 && Comparer<T>.Default.Compare(value, upperValue) <= 0;
Demo
Demo
private static void BetweenItems()
{
List<string> periods = new List<string>
{
"2010 FYA",
"2011 FYA",
"2012 FYA",
"2013 FYA",
"1Q 2014A",
"2Q 2014A",
"3Q 2014A",
"4Q 2014A",
"2014 FYA"
};
var result = periods.BetweenItems("2010 FYA", "3Q 2014A");
if (result is not null)
{
foreach (var item in result)
{
Debug.WriteLine(item);
}
}
else
{
Debug.WriteLine("Start or end value not located");
}
}
Returns
2010 FYA
2011 FYA
2012 FYA
2013 FYA
1Q 2014A
2Q 2014A
3Q 2014A
Extension class
public static class Extensions
{
public static List<string> BetweenItems(this List<string> sender, string startValue, string endValue)
{
var startIndex = sender.IndexOf(startValue);
var endIndex = sender.IndexOf(endValue) - startIndex +1;
return startIndex == -1 || endIndex == -1 ? null : sender.GetRange(startIndex, endIndex);
}
}