Reputation: 1268
In my project we are getting different list and array of elements and need to pick alternative for those list and array for example if my list consist of
string[] toys= { "car", "bat-mask", "halloween-toys", "marvel-toys", "transformer" };
now it may be a list of hundreds of elements my problems is to choose alternative from above list like if i have configuratioin to pick one after another i.e car after that skip bat-mask and pick halloween-toys
this is my first priority and after that i make it configurable like how many item to skip in between like one item or two items etc.
Reason to use it as extension because it will be use inside complete app and i simply need it access like var myList = toys.customExtensionMethods();
Upvotes: 2
Views: 2288
Reputation: 320
public static class EnumerableExtensions
{
public static IEnumerable<T> PickAlternate<T>(this IEnumerable<T> source, int skip)
{
int? currentlySkipped = null;
foreach (var item in source)
{
if (!currentlySkipped.HasValue || currentlySkipped == skip)
{
currentlySkipped = 0;
yield return item;
}
else
{
currentlySkipped++;
}
}
}
}
Upvotes: 0
Reputation:
You can use that:
using System.Linq;
static public class IEnumerableHelper
{
static public IEnumerable<T> customExtensionMethods<T>(this IEnumerable<T> items,
T takeFirst,
int skipCount)
{
var list1 = items.SkipWhile(item => !item.Equals(takeFirst));
var list2 = list1.Skip(skipCount + 1).Take(1);
return list1.Take(1).Concat(list2);
}
}
Test 1
static void Test()
{
string[] toys = { "car", "bat-mask", "halloween-toys", "marvel-toys", "transformer" };
var list = toys.customExtensionMethods("car", 1);
foreach ( var item in list )
Console.WriteLine(item);
}
Output:
car
halloween-toys
Test 2
var list = toys.customExtensionMethods("bat-mask", 2);
Output
bat-mask
transformer
Upvotes: 2
Reputation: 1720
If i am not wrong, inside your extension method you want to get array element with no Of skip value passed.
public static class ExtensionMethod
{
public static string[] CustomExtensionMethods(this string[] myData, int NoofSkip)
{
var newData = new List<string>();
for (int i = 0; i < myData.Length; i++ )
{
newData.Add(myData[i]);
i = i + NoofSkip;
}
return newData.ToArray();
}
}
Call Method:
var data = toys.CustomExtensionMethods(1);
OutPut:
{ "car", "halloween-toys", "transformer" };
Upvotes: 2
Reputation: 18155
I hope I understood your question correctly. You are intending to create an extension method which takes an input 'searchterm' and a count skip count. The method searches for the item in the list, skips the next n items and returns the new item. You could do as the following.
public static class Extensions
{
public static T PickAlternative<T>(this IEnumerable<T> source,string item,int skipCount)
{
return source.SkipWhile(x=> !x.Equals(item)).Skip(skipCount).First();
}
}
Example,
toys.PickAlternative("bat-mask",3);
toys.PickAlternative("car",2);
Output
transformer
halloween-toys
Upvotes: 0