Replace the item in collection with a new item [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have a observablecollection Named A with properties id,age,name, Am storing the changed things in another collection B. Now I want to replace the same item in object A with that of changed things in B .How can I achieve it.
foreach(var item in A)
{
}

You can use the Zip operator
ObservableCollection<ObjType> obsCollectionA = new ObservableCollection<ObjType>();
ObservableCollection<ObjType> obsCollectionB = new ObservableCollection<ObjType>();
foreach (var pair in obsCollectionA.Zip(obsCollectionB, (a, b) => new { A = a, B = b }))
{
pair.A.Id = pair.B.Id;
pair.A.Name = pair.B.Name;
pair.A.Age = pair.B.Age;
}

Assuming from "yes, I need to replace the items in B with the same index of A"
for(int i = 0; i < A.Count; i++)
{
B[i] = A[i]; //or A[i] = B[i];
// You could compare by: if(A[i].ID == B[i].ID)
}

You can follow this way:
public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
if (indexB > -1 && indexB < list.Count)
{
T tmp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = tmp;
}
return list;
}

Related

(check(k.ToString() == 1)) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a maybe simple problem. When i start program it show "Operator '==' cannot be applied to operands of type 'string' and 'int'. I dont know what to do with it. Thanks for every help.
Here is code:
class Program
{
static bool check(string input_number)
{
for (int i = 0; i < input_number.Length / 2; i++)
if (input_number[i] != input_number[input_number.Length - i - 1])
return false;
return true;
}
static void Main(string[] args)
{
var results = from i in Enumerable.Range(100, 900)
from j in Enumerable.Range(i, 1000 - i)
let k = i * j
where (check(k.ToString() == 1)
orderby k descending
select new { i, j, k };
var highestResult = results.FirstOrDefault();
if (highestResult == null)
Console.WriteLine("There are no palindromes!");
else
Console.WriteLine($"The highest palindrome is {highestResult.i} * {highestResult.j} = {highestResult.k}");
Console.ReadKey();
}
}
You are trying to compare strings (k.ToString() with numbers (1). In your case, I think, you need to do this: where check(k.ToString()) == true).
You can't compare a string and an int directly, due to C#'s strong typing. Instead, you should "convert" the int to a string, using ToString.
edit: or just not call ToString on k?

How to sort a List<Process> by Window Title [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am sure I would do this, but the way I am thinking how to achieve this makes me sad, so I am asking for better way
List<Process> myList = new List<Process>();
Process[] processlist = Process.GetProcesses(); // Load all existing processes
// Pin existing sessions to the application
foreach (Process p in processlist)
{
if (p.MainWindowTitle.Contains("TX")) // schema is like TX1 => TX10, but this loop is not sorted at all
{
myList.Add(p); // Unsorted list when looking by MainWindowTitle property
}
}
Sorry fot nor precising the question about what kind of sorting I want to achieve
[0] TX1
[1] TX2
...
[5] TX6
etc.
You could try something like this:
var myList = processlist.Where(p=>p.MainWindowTitle.Contains("TX"))
.OrderBy(p=>p.MainWindowTitle)
.ToList();
How about using LINQ's OrderBy and a simple custom comparer. In this case this might be enough. From the information you gave us it should work for you.
class Program
{
static void Main(string[] args)
{
var names = new string[] { "TX2", "TX12", "TX10", "TX3", "TX0" };
var result = names.OrderBy(x => x, new WindowNameComparer()).ToList();
// = TX0, TX2, TX3, TX10, TX13
}
}
public class WindowNameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
string pattern = #"TX(\d+)";
var xNo = int.Parse(Regex.Match(x, pattern).Groups[1].Value);
var yNo = int.Parse(Regex.Match(y, pattern).Groups[1].Value);
return xNo - yNo;
}
}
The WindowNameComparer reads (parses) the numbers attached to the TX and calculates the difference which is then used for sorting according to this table for the IComparer.Compare Method
Value Meaning
Less than zero x is less than y.
Zero x equals y.
Greater than zero x is greater than y.
Well, I made this almost without linq, but I guess it's overkill
Process temp = null;
for (int i = 0; i < Games.Count; i++)
{
for (int sort = 0; sort < Games.Count - 1; sort++)
{
string title1 = Games[sort].MainWindowTitle;
string title2 = Games[sort+1].MainWindowTitle;
int titleAsIntSum1 = title1.Sum(b => b); // This will work in this case
int titleAsIntSum2 = title2.Sum(b => b);
if (titleAsIntSum1 > titleAsIntSum2)
{
temp = Games[sort + 1];
Games[sort + 1] = Games[sort];
Games[sort] = temp;
}
}
}

how to count heapsort key comparisons [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I wrote a little C# command application. Four arrays are supposed to be sorted with a heapsort algorithm. I took an algorithm from a website and its running just fine. Now I want to count the key-comparisons the algorithm needs to sort one array. I tried to count the comparisons via for loop but its seems to be wrong... Any ideas where I have to count for it?
Here's my sorting algorithm method. GlobalVar.CountVal is simply a public static int property.
public static void HeapSort(int[] array, int arr_ubound)
{
int i, j;
int lChild, rChild, pNode, root, temp;
root = (arr_ubound - 1) / 2;
for (j = root; j >= 0; j--)
{
for (i = root; i >= 0; i--)
{
GlobalVar.CountVal += 1;
lChild = (2*i)+1;
rChild = (2*i)+2;
if ((lChild <= arr_ubound) && (rChild <= arr_ubound))
{
if (array[rChild] >= array[lChild])
pNode = rChild;
else
pNode = lChild;
}
else
{
if (rChild > arr_ubound)
pNode = lChild;
else
pNode = rChild;
}
if (array[i] < array[pNode])
{
temp = array[i];
array[i] = array[pNode];
array[pNode] = temp;
}
}
}
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
}
Here's the full code: http://pastebin.com/4Y0NQECP
By using this comparer instead of the comparison operators (>= and <), you can count the comparisons properly.
public class CountingComparer<T> : Comparer<T>
{
public int Count { get; private set; }
IComparer<T> defaultComparer = Comparer<T>.Default;
public override int Compare(T left, T right)
{
this.Count++;
return defaultComparer.Compare(left, right);
}
}
To use a comparer like this, here's how you modify your code:
x [op] y // becomes
comparer.Compare(x, y) [op] 0
// e.g.
if (array[rChild] >= array[lChild]) // becomes
if (comparer.Compare(array[rChild], array[lChild]) >= 0)
Then just make sure that you use this comparer for every comparison in the heapsort (but only in that one sorting). The full code (as I ran in LINQPad) is at http://pastebin.com/UXAQh9B3. I changed your method from hardcoded to generic to more easily identify where the comparer needed to be used.
The comparison counts for your data are as follows:
1 - 652
2 - 652
3 - 0
4 - 155

More efficient looping? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
So I'm writing a simple struct to act like an Array of strings but with some handy operators and other functions that I've always wanted to see in strings. Specifically the method I'm working on right now is the / operator. The problem is, it won't add on any remainders at the end like I want it to.
What it's supposed to do, is take an array of strings, like {"Hello", "Test1", "Test2", "Goodbye", "More?", "Qwerty"} and, say I want to divide by 4, it should return { {"Hello", "Test1", "Test2", "Goodbye"}, {"More?", "Qwerty"} } but it doesn't.
The whole class (the method I want to improve is the / operator, but if you see anything else I can work on please point it out) (I know barely any of it is commented. Sorry about that, didn't expect anyone else to see this code aside from me.):
public struct StringCollection
{
private String[] value;
public StringCollection(params String[] s)
{
this.value = s;
}
public StringCollection(StringCollection current, String ad)
{
if (current.value == null) {
current.value = new String[0] { };
}
this.value = new String[current.value.Length+1];
for (int i=0; i<this.value.Length; i++)
{
try {
this.value[i] = current[i];
} catch {
break;
}
}
this.value[this.value.Length-1] = ad;
}
public StringCollection(StringCollection x, params StringCollection[] y)
{
this.value = x.value;
for (int j=0;j<y.Length;j++)
{
for (int i=0;i<y[j].value.Length;i++)
{
this += y[j][i];
}
}
}
public static StringCollection[] operator /(StringCollection x, int y)
{
StringCollection[] result = null;
if (((int)x.value.Length/y) == ((double)x.value.Length)/y)
result = new StringCollection[y];
else
result = new StringCollection[y+1];
for (int j=0;j<y;j++)
{
for (int i=0;i<((int)x.value.Length/y);i++)
{
result[j] += x.value[i+(int)((x.value.Length/y)*j)];
}
}
if (((int)x.value.Length/y) != ((double)x.value.Length)/y)
{
// This is the part that isn't working.
for (int i=0;i<(((int)x.value.Length/y)*result[0].value.Length)-x.value.Length;i++)
{
result[result.Length-1] += x.value[i+((result[0].value.Length)*result.Length-2)];
}
}
return result;
}
public String this[int index]
{
get {
return this.value[index];
}
set {
this.value[index] = value;
}
}
}
What it does is basically takes your array (single array) and splits it into a bunch of arrays that are the same size, then it adds on the remainder in a new array at the end.
Firstly your question isn't really related to loops at all, or at least loops are only addressed in your code. You should have titled this differently.
Secondly your array adding/removing could be improved; i.e. adding 1 to array size every time and removing 1 then re-copying the entire array every time is a time-sink.
Now onto your question, your code should basically look like this:
//Make your return array
int retLen = x.Length / y;
//Add space for the remainder
if(x.Length % y != 0)
retLen++;
var ret = new StringCollection[retLen];
//Reusing variables is a good way to save memory, but watch naming conventions as this can be confusing
retLen = 0;
var tempCollection = new StringCollection();
for (int i = 0; i < x.Length; i++)
{
tempCollection = new StringCollection(tempCollection, x[i]);
if(i % y == 0 || i == x.Length - 1)
{
ret[retLen++] = tempCollection;
tempCollection = new StringCollection();
retLen = 0;
}
}
return ret;
I really don't like that you don't have a Add function in this struct, just so we're clear. the tempCollection = new StringCollection(tempCollection, x[i]); is f$*kin' TERRIBLE when it comes to time CPU time to create all those new objects.
Pretty sure you'll need to tweak that to make sure all items are entered properly, but that was a first attempt, so ... meh o.O Figured since no one was actually going to answer you I'd take the time.
EDIT: Found a bug, forgot to set retLen back to 0 when adding to ret

Chunk IEnumerable/ICollection Class C# 2.0 [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am dealing with trying to chunk up items in a custom collection class that implements IEnumerable (and ICollection) in C# 2.0. Let's say, for example, that I only want 1000 items at a time and I have 3005 items in my collection. I've got a working solution that I demonstrate below, but it seems so primitive that I figure there has to be a better way to do this.
Here's what I have (for example's sake, I'm using C# 3.0's Enumerable and var, just replace those references with a custom class in your mind):
var items = Enumerable.Range(0, 3005).ToList();
int count = items.Count();
int currentCount = 0, limit = 0, iteration = 1;
List<int> temp = new List<int>();
while (currentCount < count)
{
limit = count - currentCount;
if (limit > 1000)
{
limit = 1000 * iteration;
}
else
{
limit += 1000 * (iteration - 1);
}
for (int i = currentCount; i < limit; i++)
{
temp.Add(items[i]);
}
//do something with temp
currentCount += temp.Count;
iteration++;
temp.Clear();
}
Can anyone suggest a more elegant way of doing this in C# 2.0? I know if this project was from the past 5 years I could use Linq (as demonstrated here and here). I know my method will work, but I'd rather not have my name associated with such ugly (in my opinion) code.
Thanks.
Firstly . yield is your friend here, and it was introduced with 2.0. Consider:
public static IEnumerable<List<T>> Chunk<T>(IEnumerable<T> source, int chunkSize)
{
List<T> list = new List<T>(chunkSize);
foreach(T item in source)
{
list.Add(item);
if(list.Count == chunkSize)
{
yield return list;
list = new List<T>(chunkSize);
}
}
//don't forget the last one!
if(list.Count != 0)
yield return list;
}
Then we're flexible in type and size, so it's nicely reusable. The only that being restricted to 2.0 means, is that we can't make it an extension method.
There are several ways you could approach this.
If you just want to associate each item with the index of the chunk it belongs to:
int processed = 0;
foreach (int item in items)
{
int chunkIndex = processed++ / CHUNK_SIZE;
ProcessItem(item, chunkIndex);
}
If you want to process items in batches, but don't need the whole chunk collection at once:
int processed = 0, count = items.Count;
List<int> chunk = new List<int>(CHUNK_SIZE);
foreach (int item in items)
{
chunk.Add(item);
if (++processed % CHUNK_SIZE == 0 || processed == count) {
ProcessChunk(chunk);
chunk.Clear();
}
}
If you want to have all chunks as a list of lists:
int processed = 0, count = items.Count;
List<List<int>> chunks = new List<List<int>>();
foreach (int item in items)
{
int chunkIndex = processed++ / CHUNK_SIZE;
if (chunks.Count == chunkIndex) {
chunks.Add(new List<int>(CHUNK_SIZE));
}
chunks[chunkIndex].Add(item);
}

Categories

Resources