Remove duplicate lines from textbox in .net 2.0 - winforms

I have a multiline text and i want to remove the duplicate lines in it. I use the following code to seperate the lines in an array.
string[] lines = txtPathological.Text.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
But there is no command lines.Distinct(). Is there a way to do that ?

This works for me...
String[] lines = { "my line 1", "my line 2", "mhyline3", "lslfkdfkjdf", "my line 2", "my line 1", "my line 1", "LKDJF" };
List<String> list = new List<String>();
foreach (String s in lines)
{
if (!list.Contains(s))
list.Add(s);
}
"list" will then contain the distict lines, which you could get back to an array using:
String[] distinctLines = list.ToArray();
If this doesn't work, I'd suspect there's something about your lines that is fooling the Contains() method. If so, you'd likely have to make a method to replace Contains(), local or extension, that would handle inspection of the line.

var lines = txtPathological.Text.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
var dLines = lines.ToList().Distinct();
Edit:
string[] lines = txtPathological.Text.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> dLines = new List<string>();
foreach (var line in lines)
{
if (!dLines.Contains(line))
{
dLines.Add(line);
}
}

You could try :
string[] lines = txtPathological.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> templines = new List<string>(lines);
List<string> tempList = new List<string>();
for (int i = 0; i < templines.Count; i++)
{
if (!tempList.Contains(lines[i])) tempList.Add(lines[i]);
}
TempList is your sorted list.
Hope it could help.

Related

How to remove row from datagrid and an array

My datagrid in WPF app. displays csv file.I want to copy csv file to an array.Remove a string from array which is same as the selected row from datagrid (comparing indexes).In the end I display the string array in second datagrid.
//Storing csv file in string array
var filePath = "csvFile.csv";
using (StreamReader file = new StreamReader(filePath))
{
while (!file.EndOfStream)
{
int selectedIndex =int.Parse(dgData.SelectedIndex.ToString());
string strResult = file.ReadToEnd();
string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> list = new List<string>(result);
list.RemoveAt(selectedIndex);
foreach (string item in list)
{
Console.WriteLine(item);
Console.ReadLine();
}
dgtest.ItemsSource = list;
}
file.Close();
}
I would appreciate correcting my code.At the moment I have an error stating:
Index is out of range.
You are complicating things. Try something like this:
const string FilePath = "csvFile.csv";
List<string> lines = File.ReadAllLines(FilePath)?.ToList();
int selectedIndex = dgData.SelectedIndex;
if (lines != null && selectedIndex > 0 && lines.Count > selectedIndex)
lines.RemoveAt(selectedIndex);
dgtest.ItemsSource = lines;

Split the string array

I know this question was absolutely answered but i did not find solution.
I get response from web-service a Json string response that is ["11,22222","33,44444"].
I try this but did not work because string include these characters [ ] and first comma is in the here 11,22
StringBuilder result = new StringBuilder();
URL url2 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
String res = new String(result);
String [] coordinates = res.split(",");
How can i separate this string like "11,22222" and "33,44444"
Just use JavaScriptSerializer.
public void Method(string json)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<string> results = js.Deserialize<List<string>>(json);
}
JsonArray jArray=new JsonArray(result);
StringBuffer s=new StringBuffer();
for(int i=0;i<jArray.length();i++)
{
s.append(jArray.getString(i));
Log.e(“singleValue”,jArray.getString(i));
}
Log.e(“responsed”,s.toString());
Since you are getting a json, you can easily convert it to JsonArray and iterate thorugh it.
Gson gson = new Gson();
JsonArray array = gson.fromJson(rd, JsonElement.class).getAsJsonArray();
for (JsonElement jsonElement : array) {
System.out.println(jsonElement.getAsString());
}
Hope this helps.

two list to json in c#

I have three list in format below and I want to convert this to json format. length of list in all data sample are same.
List<string> data1=new List<string>{"col1","Col2","Col3",...}
List<string> data2=new List<string>{"a","b","c"...}
List<string> data3=new List<string>{"d","e","f"...}
I want to convert this data into json format where data1 is always to be key and other list to be value. I am expecting output something like
COnvertedSon = [{"col1":"a","col2":"b","col3":"c",....},
{"col1":"d","col2":"e","col3":"f"....}]
This should work for you:
List<string> data1 = new List<string> {"col1", "Col2", "Col3"};
List<string> data2 = new List<string> {"a", "b", "c"};
List<string> data3 = new List<string> {"d", "e", "f"};
List<dynamic> list = new List<dynamic>();
var item1 = new ExpandoObject() as IDictionary<string, Object>;
var item2 = new ExpandoObject() as IDictionary<string, Object>;
foreach (var item in data1)
{
item1.Add(item, string.Empty);
item2.Add(item, string.Empty);
}
var keys = item1.Keys.ToArray();
for (int i = 0; i < keys.Length; i++)
{
var key = keys[i];
item1[key] = data2.ElementAt(i);
item2[key] = data3.ElementAt(i);
}
list.Add(item1);
list.Add(item2);
var result = JsonConvert.SerializeObject(list);
This doesn't include any error or null checking whatsoever and assumes that the lenghts of all Lists is the same.
Try by using the following code
var json = JsonConvert.SerializeObject(list,
Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});

NancyFX Post - Bind to Object with List Parameter

I am using Nancy and I have created a basic model with a List property on it. When I use the below GET method I get the expected JSON output. However when I try to POST back the same JSON I end up with an object with and empty list of strings. I created two properties just to verify that my issue wasn't because of instantiating the DataPoints parameter to a new List in the constructor. Does anyone have any ideas on why this isn't returning properly?
JSON Object Returned from Initial Get
{
"dataPoints": [
"0",
"1",
"2",
"3",
"4"
],
"dataPoints2": [
"0",
"1",
"2",
"3",
"4"
]
}
JSON Object Returned from Post:
{
"dataPoints": [],
"dataPoints2": []
}
Class:
public class BasicModel
{
private List<string> _dataPoints;
public List<string> DataPoints
{
get
{
if (_dataPoints == null)
{
_dataPoints = new List<string>();
}
return _dataPoints;
}
set
{
_dataPoints = value;
}
}
public List<string> DataPoints2 { get; set; }
public BasicModel()
{
DataPoints2 = new List<string>();
}
public BasicModel(int idx)
{
DataPoints2 = new List<string>();
for (int i = 0; i < idx; i++)
{
DataPoints.Add(i.ToString());
DataPoints2.Add(i.ToString());
}
}
}
Get Method:
Get["/basicModel/{idx}"] = parameters =>
{
int idx = Convert.ToInt32(parameters["idx"].ToString());
BasicModel m = new BasicModel(idx);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};
Post Method:
Post["/basicmodel"] = parameters =>
{
BasicModel m = new BasicModel();
this.BindTo(m);
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};
You may be running into a know issue with BindTo create a new instance even though you give one.
You should be able use Bind instead of BindTo though and have bind return a new object:
Post["/basicmodel"] = parameters =>
{
BasicModel m = this.Bind();
return Negotiate
.WithStatusCode(HttpStatusCode.OK)
.WithModel(m)
.WithView("default");
};

Windows Phone 8 mp3 playing problems

I am trying to play mp3 in my wp 8 app, i think forgot something, can you please help
my simplified code is as it goes:
in page.xaml.cs code is:
public void Play(object sender, RoutedEventArgs e)
{
if (PlayState.Playing == BackgroundAudioPlayer.Instance.PlayerState)
{
BackgroundAudioPlayer.Instance.Pause();
}
else
{
BackgroundAudioPlayer.Instance.Play();
}
}
in App.xaml.cs code is:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = new string[] { "song.mp3"};
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = "Sounds/" + _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
{
int chunkSize = 4096;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}
}
i can see that my BackgroundAudioPlayer.Instancestate never changes, but I can't figure out why (play function is trigered)
You need to tell the BackgroundAudioPlayer which track to play.
Something like:
var track = new AudioTrack(
new Uri("/song.mp3", UriKind.Relative),
"song name",
"artist name",
"album name",
null); // no artwork
BackgroundAudioPlayer.Instance.Track = track;
BackgroundAudioPlayer.Instance.Play();

Resources