//
foreach with a "manual" index
int index = 0;
foreach (var item in
collection)
{
DoSomething(item,
index);
index++;
}
//
normal for loop
for (int index = 0; index <
collection.Count; index++)
{
var
item = collection[index];
DoSomething(item,
index);
}
|
It’s something that has always annoyed me;
couldn’t we have the benefits of both foreach and for?
It turns out that there’s a simple solution,
using Linq and tuples. Just write an extension method like this:
using System.Linq;
...
public static IEnumerable<(T item, int
index)> WithIndex<T>(this IEnumerable<T> source)
{
return
source.Select((item, index) => (item, index));
}
|
Do this:
foreach (var (item, index) in
collection.WithIndex())
{
DoSomething(item,
index);
}
|
Multilist collection by Tuple
IList<Tuple<string, string, string, string, string>> listOfData = new List<Tuple<string, string, string, string, string>>();
foreach (var item in
interactionDataSetInformation)
{
listOfData.Add(new Tuple<string, string, string, string, string>(item.ICNOcurs,
item.MessageType, item.Revision, item.EntityState, item.EntityStatus));
}
Multilist collection by ArrayList
ArrayList listOfData = new
ArrayList();
foreach (var item in
interactionDataSetInformation)
{
listOfData.Add(new string[] { item.ICNOcurs,
item.MessageType, item.Revision, item.EntityState, item.EntityStatus });
}
ArrayList listOfData =
interactionDataSetInformation.ToArrayList<InteractionDataSetInformation>();
Extension methods
public static DataTable ToDataTable<T>(this IEnumerable<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType)
?? prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor
prop in properties)
row[prop.Name] =
prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
public static List<T> ToList<T>(this ArrayList arrayList)
{
List<T> list = new List<T>(arrayList.Count);
foreach (T instance in arrayList)
{
list.Add(instance);
}
return list;
}
public static ArrayList ToArrayList<T>(this IEnumerable<T> list)
{
ArrayList arrayList = new
ArrayList();
foreach (T item in list)
{
List<string> listString = new List<string>();
foreach (PropertyInfo
prop in typeof(T).GetProperties())
{
listString.Add((prop.GetValue(item) == null) ? string.Empty :
prop.GetValue(item).ToString());
}
string[] _item = listString.ToArray();
arrayList.Add(_item);
}
return arrayList;
}
}
-------------------------------------------------------------------------------------------------------------------------
No comments:
Post a Comment