finding amount of same texts [closed] - c#

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 months ago.
Improve this question
hello I am making a survival game but I don't know how to make if there is some same text in a string it deletes it and then makes it to
<amount><item.title>
here is the code
string[] needs = new string[items.Length];
string text = "";
for (int i = 0; i < items.Length; i++)
{
text += items[i].title + ",";
}

If you're trying to create a string without duplicates based on your list of items, you can first create another list of items that doesn't contain duplicates. You will need LINQ for this.
var distinctItemGroups = items.GroupBy(item => item.Title);
I would also recommend using a StringBuilder for the text. You can then do something like this:
var displayText = new StringBuilder();
foreach (var group in distinctItemGroups)
{
displayText.Append(group.First().Title + ", ");
}
To actually display the text from the StringBuilder just call ToString() on it.

I think you need:
Create a class for count items
public class MyResultModel
{
public string Title { get; set; }
public int Count { get; set; }
public override string ToString()
{
return $"{Count}{Title}";
}
}
And fill the items with
IEnumerable<MyResultModel> myModels = items.GroupBy(x => x)
.Select(x => new MyResultModel() { Count = x.Count(), Title = x.Key });
Then you can generate a string:
string result = string.Join(",", myModels.Select(x=> x.ToString()));

Related

Kattis - Recount C# [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 10 months ago.
Improve this question
I'm trying to solve https://open.kattis.com/problems/recount in C#. I have my code written but I know I'm missing something but I'm stuck and I've been working on this for a few days. Whenever I try to run my code I receive a runtime error and I know it's because I need to be able to add a user inputted list to convert to a dictionary but I'm not sure how.
Running on .NET 3.1 for school
Here is the code I have currently
namespace Kattis_Solution___Recount
{
class Program
{
static void Main(string[] args)
{
SortedDictionary<string, int> votes = new SortedDictionary<string, int>();
List<string> names = new List<string>();
string name = "";
name = Console.ReadLine();
Console.Write(name);
Console.Write("\n");
int max = 0;
string winner = "";
while (name[0] != '*')
{
if (votes[name] == 0)
{
names.Add(name);
}
votes[name]++;
if (votes[name] > max)
{
max = votes[name];
winner = name;
}
name = Console.ReadLine();
Console.Write(name);
Console.Write("\n");
}
Console.Write(winner);
Console.Write("\n");
for (int i = 1; i < names.Count; i++)
{
if (votes[names[i]] == max && winner != names[i])
{
Console.Write("Runoff!");
Console.Write("\n");
break;
}
}
}
}
}
You cannot do this if the entry isnt there
if (votes[name] == 0) {
names.Add(name);
}
(unlike some other languages - c++ for example)
You need to do
if (!votes.ContainsKey(name)) {
names.Add(name);
votes[name] = 0;
}
See docs here https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.item?view=net-6.0
The value associated with the specified key. If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

How to assign data from CSV into Object [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
so far I have this one which works really good.
private static MovieItem readCSV(string path)
{
var yourData = File.ReadAllLines(path)
.Skip(1)
.Select(x => x.Split(';'))
.Select(x => new Movie
{
GUID = x[0],
Title = x[1],
ISBN = x[2],
CreatedTime = DateTime.Now,
AuthorInformation = new AuthorInformation()
{
Id = Guid.NewGuid().ToString(),
Name = x[4],
Address = x[5],
Age = x[6]
}
}).ToArray();
return yourData[0];
}
My question is, is there a better way to assign the object?
So far I have like GUID = x[0], Title = x[1] and so on... it's not good because the header in the first row can change, so I want to be flexible.
Is there a way to assign e.g. GUID to the CSV header named GUID?
Like looking for the header name and if it is equal GUID, assign the content to GUID?
CSV File:
I've commented your question that already but here's a sample code:
1- Make a class and name it "Book" or whatever convenient. It's fields would be GUID, Title, ISBN, etc..
public class Book //I'm showing only one field of the class
{
private string title;
public string Title { get; set;}
public Book() {}
}
2-Read your CSV file onetime where you will read the first line only and split it to a string[] array -your splitter is ";"- and store the index of each field to a variable (Switch statement would be very helpful here)
public struct Headers //use it to store the index of each field in the file only title is shown here
{
public int title;
}
string[] rowSplitter = new string[] { "\r\n" };
string[] colSplitter = new string[] { ";" };
//Inside a method for reading the file use the following code
string[] csvData = File.ReadAllText(csvFile).Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries);
string[] headerRow = csvData [0].Split(colSplitter, StringSplitOptions.None);
Headers column = new Headers();
for (int i = 0; i < headerRow.Length; i++)
{
switch (headerRow[i].ToLower())
{
case "title":
column.title = i;
break;
}
}
3- Use a loop to go through all the lines, Split by ";" again, and inside this loop instantiate a Book() object with corresponding data cuz now you know the index of each data item -the variables I mentioned.
for (int i = 1; i < csvData.Length; i++)
{
string[] currentRow = csvData[i].Split(colSplitter, StringSplitOptions.None);
Book bookItem = new Book();
bookItem.Title = currentRow[column.title];
//Here you can do whatever you like with this bookItem on-the-fly or if you want to keep it to the end of your code add it to a list.
}
//reading all the lines(rows) from the file.
string[] rows = File.ReadAllLines(Directory.GetFiles(#"D:\CSV\test.csv"));
DataTable dtData = new DataTable();
string[] rowValues = null;
DataRow dr = dtData.NewRow();
//Creating columns
if (rows.Length > 0)
{
foreach (string columnName in rows[0].Split(','))
dtData.Columns.Add(columnName.Replace(" ", "").ToLower());
}
//Creating row for each line.(except the first line, which contain column names)
for (int row = 1; row < rows.Length; row++)
{
rowValues = rows[row].Split(',');
dr = dtData.NewRow();
dr.ItemArray = rowValues;
dtData.Rows.Add(dr);
}

Replace the item in collection with a new item [closed]

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;
}

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;
}
}
}

display value of database [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 9 years ago.
Improve this question
i have code like this
Global.dbCon.Open();
int idQuestion;
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
//messageBox.Show(idQuestion.ToString()); -->first message box
}
}
//messageBox.Show(idQuestion.ToString()); -->second message box
Global.dbCon.Close();
i don't have problem to display first messagebox, but how to display second messagebox
edited
i try to make code from #rhughes become a function (class) like this following code
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions) {
return id;
}
but it's no work because not all code paths return a value...i wonder how corret way to do it?
Try something like this:
Global.dbCon.Open();
List<int> idQuestions = new List<int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
idQuestions.Add(idQuestion);
}
}
Global.dbCon.Close();
foreach (int id in idQuestions)
{
messageBox.Show(id.ToString());
}
What we are doing here is adding all of the question ids into a list and then displaying each of them afterwards.

Categories

Resources