I am trying to figure out a way to correctly sort a bunch of different arraylists.
I am publishing content articles and every value [0] in an arraylist will relate to every other value [0]. and so on. Each element makes up the collective parts of a complete content item.
Now, the last element, popularity, is the amount of clicks an item has received. How do I
do a sort of the content items based on popularity without mixing up the html for each article?
*EDIT I am limited by the .NET 2.0 Framework at Work*
Below is the code... thanks.
public class MultiDimDictList : Dictionary<string, ArrayList> { }
myDicList.Add("fly", a_fly);
myDicList.Add("img", a_img);
myDicList.Add("bar", a_bar);
myDicList.Add("meter", a_meter);
myDicList.Add("block", a_block);
myDicList.Add("popularity", a_pop);
If you use the following code you can convert your existing dictionary of arraylists into a collection of Dictionaries and thus allowing a simple sort using Linq OrderBy
// Get the shortest arraylist length (they should be equal this is just a paranoia check!)
var count=myDicList.Values.Min(x=>x.Count);
// Get the collection of Keys
var keys=myDicList.Keys;
// Perform the conversion
var result=Enumerable.Range(0,count).Select(i=>keys.Select(k=>new {Key=k,Value=myDicList[k][i]}).ToDictionary(x=>x.Key,x=>x.Value));
var sorted=result.OrderByDescending(x=>x["popularity"]).ToList()
-- EDIT VERSION FOR .NET 2.0
First you need a comparer class
class PopularityComparison : IComparer<Dictionary<string,object>> {
private bool _sortAscending;
public PopularityComparison(bool sortAscending) {
_sortAscending = sortAscending;
}
public int Compare(Dictionary<string, object> x, Dictionary<string, object> y) {
object xValue = x["popularity"];
object yValue = y["popularity"];
// Sort Ascending
if (_sortAscending) {
return Comparer.Default.Compare(xValue, yValue);
} else {
return Comparer.Default.Compare(yValue, xValue);
}
}
}
Then you can use the following code
// Get the shortest arraylist length (they should be equal this is just a paranoia check!)
// Replacement for min
int count = int.MaxValue;
foreach (ArrayList a in myDicList.Values) if (a.Count < count) count = a.Count;
// Get the collection of Keys
Dictionary<string, ArrayList>.KeyCollection keys = myDicList.Keys;
// Perform the conversion
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>(count);
for (int i = 0; i < count; i++) {
Dictionary<string, object> row = new Dictionary<string, object>(keys.Count);
foreach (string key in keys) row.Add(key, myDicList[key][i]);
result.Add(row);
}
And then finally to sort in ascending popularity order
result.Sort(new PopularityComparison(true));
or Descending order
result.Sort(new PopularityComparison(true));
I'd think it would be better to have an object containing your keys as properties, then a single collection with each item you'd have in your array lists.
This way you'd have a single collection sort, which becomes trivial if using Linq.OrderBy().
something like...
public class Article
{
public string Fly{get;set;}
public string Img{get;set;}
// etc.
public float Popularity{get;set;}
}
Then...
List<Article> articles = ... get from somewhere, or convert from your array lists.
List<Article> sorted = articles.OrderBy(a=>a.Popularity).ToList();
Please excuse the napkin code here... I'll update it if you need more detail.
An example using non-linq.
Create an implementation of IComparer.
public class ArticleComparer : IComparer<Article>
{
public bool Accending { get; set; }
public int Compare(Article x, Article y)
{
float result = x.Popularity - y.Popularity;
if (!Accending) { result *= -1; }
if (result == 0) { return 0; }
if (result > 0) return 1;
return -1;
}
}
Then when you go to sort the List, you can do something like the following.
ArticleComparer comparer = new ArticleComparer();
comparer.Accending = false;
articles.Sort(comparer);
This would be much easier if you had a list of article objects, each of which contained properties for fly, img, bar, popularity, etc. But if you really have to store things using this inside-out approach, then the only way you can sort the content items based on popularity is to create another array (or list) to hold the order.
Create a new list and populate it with sequential indexes:
List<int> OrderedByPopularity = new List<int>();
ArrayList popList = myDicList["popularity"];
for (int i = 0; i < popList.Count; ++i)
{
OrderedByPopularity.Add(i);
}
Now you have a list that contains the indexes of the items in the popularity list. Now you can sort:
OrderedByPopularity.Sort((i1, i2) => return popList[i1].CompareTo(popList[i2]););
But that gives you the least popular article first. If you want to reverse the sort so that OrderedByPopularity[0] is the most popular item:
OrderedByPopularity.Sort((i1, i2) => { return popList[i2].CompareTo(popList[i1]);});
Really, though, you should look into restructuring your application. It's much easier to work with objects that have properties rather than trying to maintain parallel arrays of properties.
If you have to do this in .NET 2.0, declare the poplist array at class scope (rather than method scope), and create a comparison method.
ArrayList poplist;
void MyMethod()
{
List<int> OrderedByPopularity = new List<int>();
popList = myDicList["popularity"];
for (int i = 0; i < popList.Count; ++i)
{
OrderedByPopularity.Add(i);
}
OrderedByPopularity.Sort(PopularityComparison);
// ...
}
int PopularityComparison(int i1, int i2)
{
return ((int)popList[i2]).CompareTo((int)popList[i1]);
}
Related
I have two record structures and two lists as follows:
public struct gtAliasRecType : ICloneable
{
public int lRecordNum;
public double dLocationCd;
}
public struct gtCVARecType : ICloneable
{
public double dLocationCd;
}
static public List<gtCVARecType> LCVARec = null;
static public List<gtAliasRecType> LAliasRec = null;
Now i want to iterate "LAliasRec" list and find whether similar "dLocationCd" exists in "LCVARec" list or not.
I tried using "Contains" and "Find" function of list1 but ended up in errors.
public static void XYZ()
{
gtAliasRecType uAliasRec = gtAliasRecType.CreateInstance();
gtCVARecType uCVARec = gtCVARecType.CreateInstance();
for (int i = 0; i < LAliasRec.Count; i++)
{
uAliasRec = LAliasRec[i];
//trying Find method
gtCVARecType c1 = LCVARec.Find(uAliasRec.dLocationCd);
//trying Contains method
bool nReturn = LCVARec.Contains( uAliasRec.dLocationCd );
}
}
However, i ran into "Cannot convert from 'double' to 'gtCVARecType' error.
Contains & Find
Thanks in advance :)
You can't use Contains to find an item of a different type. You can use Find, but I'd personally use the LINQ Any method:
foreach (var uAliasRec in LAliasRec)
{
bool nReturn = LCVARec.Any(rec => rec.dLocationCd == uAliasRec.dLocationCd);
// Presumably do something with nReturn
}
If the lists are large, you might want to create a HashSet<double> for all the locations first, which is an up-front cost that will make everything else cheaper:
HashSet<double> locations = new HashSet<double>(LCVARec.Select(rec => rec.dLocationCd));
foreach (var uAliasRec in LAliasRec)
{
bool nReturn = locations.Contains(uAliasRec.dLocationCd);
// Presumably do something with nReturn
}
As an aside, I'd strongly advise you to start following regular .NET naming conventions. In its current form, your code is going to be very hard for anyone used to regular C# code to work with.
What about using Intersect
var results = LAliasRec
.Select(x => x.dLocationCd)
.Intersect(LCVARec.Select(x => x.dLocationCd));
bool exists = results.Count() > 0;
Select only the double values, and get intersected ones. If Count greater than 0, you got mutual property values.
You can use LINQ and Inner join to find the intersection of two lists.
var query = from lcva in LCVARec
join lAlias in LAliasRec on lcva.dLocationCd equals lAlias.dLocationCd
select lcva;
Console.WriteLine(query.Count()); //prints number of matching items.
Update
If you can change the List<T> to SortedList<TKey, TValue> of SortedDictionary<TKey, TValue> it will help in quicker lookup.
If you prefer to use Contains() you must implement IEquatable<T> and if you want performance you have to Sort() which needs the class to have IComparable<T> and then do BinarySearch
Reference : https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netcore-3.1#remarks
I have a method that finds differences between two lists of ints using a dictionary. Essentially the code loops the first list, adding each int to the dictionary and setting (to 1 where not already present)/incrementing the value. It then loops the second list setting (to -1 where not already present)/decrementing the value.
Once it has looped both lists you end up with a dictionary where keys with values = 0 indicate a match, keys with values >=1 indicate presence only in the first list and values <=-1 indicate presence only in the second list.
Firstly, is this a sensible implementation?
Secondly, I would like to make it more generic, at the moment it can only handle int based lists. I'd like something that could handle any object where the caller could potentially define the comparison logic...
public static Dictionary<int, int> CompareLists(List<int> listA, List<int> listB)
{
// 0 Match
// <= -1 listB only
// >= 1 listA only
var recTable = new Dictionary<int, int>();
foreach (int value in listA)
{
if (recTable.ContainsKey(value))
recTable[value]++;
else
recTable[value] = 1;
}
foreach (int value in listB)
{
if (recTable.ContainsKey(value))
recTable[value]--;
else
recTable[value] = -1;
}
return recTable;
}
Thanks in advance!
In response to:
"It won't work properly if to example you have same value appears twice in listA and once in listB, result will be positive, which say "listA only" in your comments."
Let me clarify; if a value appears twice in listA it should also appear twice in listB - So if a value is in listA twice and once in listB, I don't care which one from listA it picks to match, as long as the one non-reconciling item is reported correctly.
Imagine the use-case where you are trying to reconcile lots of payment amounts between two files, it's entirely feasible to have repeating amounts but it doesn't really matter which of the duplicates are matched as long as the non-reconciling values are reported.
To answer your second question, here's how to make it more generic:
public static Dictionary<T, int> CompareLists<T>(IEnumerable<T> listA,
IEnumerable<T> listB, IEqualityComparer<T> comp)
{
var recTable = new Dictionary<T, int>(comp);
foreach (var value in listA)
{
if (recTable.ContainsKey(value))
recTable[value]++;
else
recTable[value] = 1;
}
foreach (var value in listB)
{
if (recTable.ContainsKey(value))
recTable[value]--;
else
recTable[value] = -1;
}
return recTable;
}
This is more generic because:
I pass in the type T instead of an int.
I use IEnumerables instead of Lists.
I pass in an IEqualityComparer and pass it to the Dictionary constructor which needs to use it.
I use var in the foreach loops instead of int. You can also use T.
You call this code like this:
static void Main()
{
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 3, 2, 1 };
var obj = CompareLists(arr1, arr2, EqualityComparer<int>.Default);
Console.ReadLine();
}
Here's an example of implementing IEqualityComparer. This treats all odd ints as equal and all even ints as equal:
public class MyEq : IEqualityComparer<int>
{
public bool Equals(int x, int y)
{
return (x % 2) == (y % 2);
}
public int GetHashCode(int obj)
{
return (obj % 2).GetHashCode();
}
}
FullOuterJoin as found here: LINQ - Full Outer Join
public static Dictionary<int, int> CompareLists(List<int> listA, List<int> listB)
{
return listA.FullOuterJoin(listB,
a=>a, // What to compare from ListA
b=>b, // What to compare from ListB
(a,b,key)=>
new {key=key,value=0}, // What to return if found in both
new {key=key,value=-1},// What to return if found only in A
new {key=key,value=1}) // What to return if found only in B
.ToDictionary(a=>a.key,a=>a.value); // Only because you want a dictionary
}
You can do this using Generics:
public static Dictionary<T, int> CompareLists<T>(List<T> listA, List<T> listB)
{
// 0 Match
// <= -1 listB only
// >= 1 listA only
var recTable = new Dictionary<T, int>();
foreach (T value in listA)
{
if (recTable.ContainsKey(value))
recTable[value]++;
else
recTable[value] = 1;
}
foreach (T value in listB)
{
if (recTable.ContainsKey(value))
recTable[value]--;
else
recTable[value] = -1;
}
return recTable;
}
These are my two cents:
public static Dictionary<T, int> CompareLists<T>(List<T> left, List<T> right, IEqualityComparer<T> comparer)
{
Dictionary<T, int> result = left.ToDictionary(l => l, l => right.Any(r => comparer.Equals(l, r)) ? 0 : -1);
foreach (T r in right.Where(t => result.Keys.All(k => !comparer.Equals(k, t))))
result[r] = 1;
return result;
}
The method takes Lists of any type T and an IEqualityComparer for that type T. It then at first generates a dictionary of those elements contained in the "left" List, thereby checking if they are also in the "right" List and setting the value accordingly.
The second step adds the elements that are only contained in the "right" List with value 1.
If this is a sensible implementation depends on what you are trying to achieve with it. I think it's a short but still readable one, relying on proper implementation of the LINQ methods. Though there might be faster possibilities one could think about if this is for really big lists or an very often called method.
I'm not very familiar with Java, and I'm a bit unsure of how to translate this from c# into java.
Dictionary<string, int> myDictionary = GetDictionary();
int N = 10;
myDictionary
.OrderByDescending(dictionaryEntry => dictionaryEntry.Value)
.Take(N)
.Select(dictionaryEntry => dictionaryEntry.Key)
.ToList();
Now, I KNOW the dictionary itself isnt being sorted, its just a new IEnumberable, and that's OK.
Thanks!
I'm not a C# guy, I've never worked with it, but if I should take a guess it seems like you are sorting the map by its values in descending order, retrieving the 10 first elements, then converting the keys of those 10 elements into a list.
If the values are known to be distinct, then it's kind of trivial - you just convert to a SortedMap with keys and values exchanged. So I'm assuming that the values are not distinct, i.e. that the same number may appear multiple times.
In that case it's not as trivial, and definitely not as simple as in your C# example. My first thought was to create a sorted set with a custom comparator, where each element in the set is a Map.Entry from your map, where the keys and values are exchanged.
This will actually require quite a bit of code in Java. Heres one attempt:
// Create a SortedSet of the reversed entry set, with a custom comparator for sorting
SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet<Map.Entry<Integer, String>>(
new Comparator<Map.Entry<Integer, String>>() {
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
// sort by key, then by value --> in descending order
int keyCompareResult = -o1.getKey().compareTo(o2.getKey()); // negate --> descending
int valueCompareResult = o1.getValue().compareTo(o2.getValue());
return keyCompareResult == 0 ? valueCompareResult : -keyCompareResult;
}
});
// Add all entries of the map to the sorted set
for (Map.Entry<String, Integer> entry : map.entrySet()) {
Map.Entry<Integer, String> reversedEntry = new AbstractMap.SimpleEntry<Integer, String>(entry.getValue(), entry.getKey());
sortedSet.add(reversedEntry);
}
// Convert the 10 first elements to the resulting list
int N = 10;
List<String> result = new ArrayList<String>(N);
Iterator<Map.Entry<Integer,String>> iterator = sortedSet.iterator();
while (iterator.hasNext() && result.size() < N) {
Map.Entry<Integer, String> entry = iterator.next();
result.add(entry.getValue());
}
I came up with pretty much the same thing as Steinar suggested, if you know of a more LINQ-y/functional way to do it, please add your answer too!
//Convert to List of Map.Entry
ArrayList<Map.Entry<String,Integer>> myArrayList = ArrayList<Map.Entry<String,Integer>>(myHashMap.entrySet());
//Natural order is ascending, so we reverse the comparator to get it Descending.
Collections.sort(myArrayList , Collections.reverseOrder(new EntryComparator()));
//Create list and add Keys
List<String> topNStrings = new ArrayList<String>();
for (int i = 0; i < N && i < myArrayList.size(); i++)
{
topNStrings.add(myArrayList.get(i).getKey());
}
and had a separate little comparator class
private class EntryComparator implements Comparator<Map.Entry<String,Integer>>
{
#Override
public int compare(Map.Entry<String,Integer> x, Map.Entry<String,Integer> y)
{
return compare(x.getValue(), y.getValue());
}
private int compare(Integer a, Integer b)
{
return a < b ? -1
: a > b ? 1
: 0;
}
}
Let us start with an arbitrary HashMap that you have acquired somehow defined by HashMap<String, Integer> map.
We want to sort the values and then get the first N values.
int N = 10;
List<Integer> values = new ArrayList<Integer>( map.values() );
Collections.sort(values);
List<Integer> N_values = values.subList(0, N);
I was trying to create a visualizer for IDictionary or ICollection
Then like the simple visualizer (without dialog; I mean the ususal string visualizer that appears when hovering the variable, see image below), I want to make my custom text, I want to cast the collection to its type's list (I.E. StringCollection to List(Of String) or List) and then I will be able to see it in the visualizer.
Or for Dictionaries show to lists visualizers for keys and for values.
Any ideas how to implement or even how to start?
I will update my question soon.
This is something I thought about:
using System.Collections.Specialized;
using System.Collections;
namespace ConsoleApplication2
{
static class Program
{
static void Main(string[] args)
{
System.Collections.Specialized.StringCollection collection = new StringCollection();
collection.AddRange(new string[] { "string1", "string2", "sting3" });
string[] visualizable = collection.ConvertToVisualizableList();
Dictionary<string,string> dic = new Dictionary<string,string>
{
{"key1","value"},
{"key2","value"}
};
string[,] visualizable2 = dic.ConvertToVisualizableDictionary();
}
static string[] ConvertToVisualizableList(this IList collection)
{
lock (collection)
{
if (collection == null) return null;
int length = collection.Count;
string[] list = new string[length];
for (int i = 0; i < length; i++)
{
object item = collection[i];
if (item != null) list[i] = item.ToString();
}
return list.ToArray();
}
}
static string[,] ConvertToVisualizableDictionary(this IDictionary dictionary)
{
if (dictionary == null) return null;
int length = dictionary.Count;
string[,] list = new string[length, 2];
int i = 0;
foreach (object item in dictionary.Keys)
{
list[i, 0] = item.ToString();
object value = dictionary[item];
if(value!=null) list[i, 1] = value.ToString();
i++;
}
return list;
}
}
}
These are VS visualizers for array and multidimentional arrays:
I want to use something similar for ICollection (or IList), IDictionary etc.
Note that in arrays, the visualizer shows every nested objcet.
This is actually what I want to achieve:
.
Try to visualize a List and you will see that there is a private value _items, so you can see its items.
I want to achieve something similar in collection and dictionary.
There are a number of examples on Code Project. This is the one i have the most experience with: DataSet Visualizer
i have installed and used it myself so i know it works. Is is more advanced than you need since it actually displays entire ADO data sets but the code should be pretty easy to modify.
Here are a couple of other links to check out as well:
Project 1
Project 2
I've found somthing that already exists:
http://www.codeproject.com/KB/macros/ListVisualizer.aspx, but it will still not show objects.
A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach without getting the exception. See Paul Jackson's blog entry An Interesting Side-Effect of Concurrency: Removing Items from a Collection While Enumerating for information on this change.
What is the best way to do the following?
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable)
{
item.Add(new item2)
}
}
Usually I use an IList as a cache/buffer until the end of the foreach, but is there better way?
The collection used in foreach is immutable. This is very much by design.
As it says on MSDN:
The foreach statement is used to
iterate through the collection to get
the information that you want, but can
not be used to add or remove items
from the source collection to avoid
unpredictable side effects. If you
need to add or remove items from the
source collection, use a for loop.
The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.
Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.
foreach(var item in Enumerable)
{
foreach(var item2 in item.Enumerable.ToList())
{
item.Add(item2)
}
}
To illustrate Nippysaurus's answer: If you are going to add the new items to the list and want to process the newly added items too during the same enumeration then you can just use for loop instead of foreach loop, problem solved :)
var list = new List<YourData>();
... populate the list ...
//foreach (var entryToProcess in list)
for (int i = 0; i < list.Count; i++)
{
var entryToProcess = list[i];
var resultOfProcessing = DoStuffToEntry(entryToProcess);
if (... condition ...)
list.Add(new YourData(...));
}
For runnable example:
void Main()
{
var list = new List<int>();
for (int i = 0; i < 10; i++)
list.Add(i);
//foreach (var entry in list)
for (int i = 0; i < list.Count; i++)
{
var entry = list[i];
if (entry % 2 == 0)
list.Add(entry + 1);
Console.Write(entry + ", ");
}
Console.Write(list);
}
Output of last example:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9,
List (15 items)
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9
As mentioned, but with a code sample:
foreach(var item in collection.ToArray())
collection.Add(new Item...);
You should really use for() instead of foreach() in this case.
You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.
The for loop is a nice alternative, but if your IEnumerable collection does not implement ICollection, it is not possible.
Either:
1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (#tvanfosson)
or
2) Keep a list of changes and commit them after the enumeration.
LINQ is very effective for juggling with collections.
Your types and structure are unclear to me, but I will try to fit your example to the best of my ability.
From your code it appears that, for each item, you are adding to that item everything from its own 'Enumerable' property. This is very simple:
foreach (var item in Enumerable)
{
item = item.AddRange(item.Enumerable));
}
As a more general example, let's say we want to iterate a collection and remove items where a certain condition is true. Avoiding foreach, using LINQ:
myCollection = myCollection.Where(item => item.ShouldBeKept);
Add an item based on each existing item? No problem:
myCollection = myCollection.Concat(myCollection.Select(item => new Item(item.SomeProp)));
Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T> members and aggregate the source list):
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
public class ModifiableList<T> : List<T>
{
private readonly IList<T> pendingAdditions = new List<T>();
private int activeEnumerators = 0;
public ModifiableList(IEnumerable<T> collection) : base(collection)
{
}
public ModifiableList()
{
}
public new void Add(T t)
{
if(activeEnumerators == 0)
base.Add(t);
else
pendingAdditions.Add(t);
}
public new IEnumerator<T> GetEnumerator()
{
++activeEnumerators;
foreach(T t in ((IList<T>)this))
yield return t;
--activeEnumerators;
AddRange(pendingAdditions);
pendingAdditions.Clear();
}
}
class Program
{
static void Main(string[] args)
{
ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });
foreach(int i in ints)
ints.Add(i * 2);
foreach(int i in ints)
Console.WriteLine(i * 2);
}
}
}
To add to Timo's answer LINQ can be used like this as well:
items = items.Select(i => {
...
//perform some logic adding / updating.
return i / return new Item();
...
//To remove an item simply have logic to return null.
//Then attach the Where to filter out nulls
return null;
...
}).Where(i => i != null);
The best approach from a performance perspective is probably to use a one or two arrays. Copy the list to an array, do operations on the array, and then build a new list from the array. Accessing an array element is faster than accessing a list item, and conversions between a List<T> and a T[] can use a fast "bulk copy" operation which avoids the overhead associated accessing individual items.
For example, suppose you have a List<string> and wish to have every string in the list which starts with T be followed by an item "Boo", while every string that starts with "U" is dropped entirely. An optimal approach would probably be something like:
int srcPtr,destPtr;
string[] arr;
srcPtr = theList.Count;
arr = new string[srcPtr*2];
theList.CopyTo(arr, theList.Count); // Copy into second half of the array
destPtr = 0;
for (; srcPtr < arr.Length; srcPtr++)
{
string st = arr[srcPtr];
char ch = (st ?? "!")[0]; // Get first character of string, or "!" if empty
if (ch != 'U')
arr[destPtr++] = st;
if (ch == 'T')
arr[destPtr++] = "Boo";
}
if (destPtr > arr.Length/2) // More than half of dest. array is used
{
theList = new List<String>(arr); // Adds extra elements
if (destPtr != arr.Length)
theList.RemoveRange(destPtr, arr.Length-destPtr); // Chop to proper length
}
else
{
Array.Resize(ref arr, destPtr);
theList = new List<String>(arr); // Adds extra elements
}
It would have been helpful if List<T> provided a method to construct a list from a portion of an array, but I'm unaware of any efficient method for doing so. Still, operations on arrays are pretty fast. Of note is the fact that adding and removing items from the list does not require "pushing" around other items; each item gets written directly to its appropriate spot in the array.
I have written one easy step, but because of this performance will be degraded
Here is my code snippet:-
for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
{
foreach (Match match in reg.Matches(lines))
{
var aStringBuilder = new StringBuilder(lines);
aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
lines[k] = aStringBuilder.ToString();
tempReg = 0;
break;
}
}