Making random number in Linq [duplicate] - c#

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 5 years ago.
Hi i writing this below code for make some person. in query i want to get all persons and select instance form every person this below code is for Main method:
Persons[] person = { new Persons(534, "Komeil", "Shahmoradi", 20, 1.65f, 68.3f),
new Persons(1047, "Ahmad", "Darvishi", 18, 1.72f, 70) ,
new Persons(56, "Javad", "Amini", 28, 1.56f, 73.2f),
new Persons(2, "Hossein", "Kiany", 17, 1.80f, 65.6f) ,
new Persons(192, "Hossein", "Kazemy", 15, 1.80f, 83.6f),
new Persons(2002, "Hossein", "Saeedi", 43, 1.80f, 93.6f)};
Random rnd = new Random();
var QpersonsLocation = from value in person
select new Duty(rnd.Next(1,2000), value.pName, value.pFamily, value.pAge);
Console.WriteLine("[/] System seting location");
foreach (var item in QpersonsLocation)
{
Console.WriteLine(item.dId +"\t" + item.dName + "\t" + item.dFamily + "\t" + item.dAge + "\t" + item.dDuttyLocation+"\t");
}
And this is for my Persons class:
class Persons
{
public long pId { get; set; }
public string pName { get; set; }
public string pFamily { get; set; }
public byte pAge { get; set; }
public float pSize { get; set; }
public float pWeight { get; set; }
public Persons(long pId, string pName, string pFamily, byte pAge, float pSize, float pWeight)
{
this.pId = pId;
this.pName = pName;
this.pFamily = pFamily;
this.pAge = pAge;
this.pSize = pSize;
this.pWeight = pWeight;
}
}
problem in the lass code for Duty class :
class Duty
{
string[] locations = {"Esfahan",
"Tehran",
"Mashhad",
"Shiraz",
"Hamedan",
"Azarbayejan"};
public long dId {get;set;}
public string dName { get; set; }
public string dFamily { get; set; }
public byte dAge { get; set; }
public string dDuttyLocation { get; set; }
public Duty(long dId, string dName, string dFamily, byte dAge)
{
this.dId = dId;
this.dName = dName;
this.dFamily = dFamily;
this.dAge = dAge;
Random rnd = new Random();
int num = rnd.Next(0,locations.Length);
dDuttyLocation = locations[num];//problem
}
}
The code working correctly but the location not saving and always dDuttyLocation equals the last number of random number this below picture shows the result:

The problem is creating new instances of the Random class too close in time in your Duty constructor. See here for more info.
Similar to how you're already doing it to generate a new dId for each person, you would need to generate the random number and pass it into the constructor so that they are not all the same.
To do that, you'd first need to make your locations array public and static. Then you can change your LINQ expression to something like:
Random rnd = new Random();
var QpersonsLocation = from value in person
select new Duty(rnd.Next(1,2000), value.pName, value.pFamily, value.pAge)
{
dDuttyLocation = rnd.Next(Duty.locations.Length)
};

Related

Except using two List [duplicate]

This question already has answers here:
Using Linq Except not Working as I Thought
(5 answers)
Closed 21 days ago.
I have two list that I want to get the different. So because CustomerId 1 is in both I only want to return CustomerId 2. I am using Exceptbut I a returning CustomerId 1 and 2 any help would be great
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
List<Participants> Participants1 = new List<Participants>();
Participants vm1 = new Participants();
vm1.CustomerId = 1;
vm1.FirstName = "Bill";
vm1.LastName= "Jackson";
Participants1.Add(vm1);
List<Participants> Participants2 = new List<Participants>();
Participants vm2 = new Participants();
vm2.CustomerId = 2;
vm2.FirstName = "Steve";
vm2.LastName= "Jackson";
Participants vm3 = new Participants();
vm3.CustomerId = 1;
vm3.FirstName = "Bill";
vm3.LastName= "Jackson";
Participants2.Add(vm2);
Participants2.Add(vm3);
var inFirstOnly = Participants2.Except(Participants1);
foreach(Participants item in inFirstOnly){
Console.WriteLine(item.CustomerId);
}
}
public class Participants
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
To only return CustomerId 2, you need to implement a custom equality comparer to compare objects based on the CustomerId property instead of the default comparison which compares references.
public class ParticipantsComparer : IEqualityComparer<Participants>
{
public bool Equals(Participants x, Participants y)
{
return x.CustomerId == y.CustomerId;
}
public int GetHashCode(Participants obj)
{
return obj.CustomerId.GetHashCode();
}
}
Usage:
var inFirstOnly = Participants2.Except(Participants1, new ParticipantsComparer());

Adding items to ObservableColletion - UWP C#

When I'm trying to add items to observable collection, it always replace all items with items added last. What is the reason for it? My code is here
public class FavoriteClassList
{
public int ID { get; set; }
public string Name { get; set; }
}
public static ObservableCollection<FavoriteClassList> _FavoriteClassList = new ObservableCollection<FavoriteClassList>();
FavoriteClassList objFavoriteClassList = new FavoriteClassList();
for (int m=1;m<=10;m++)
{
objFavoriteClassList.ID = m;
objFavoriteClassList.Name = "Name"+m;
_FavoriteClassList.Add(objFavoriteClassList);
}
Now when printing values of AppGlobals._FavoriteClassList it shows 10 items. But ID and Name of each items is always 10 and Name10 respectively.
You added one object 10 times and rewrite it 10 times. Here is a fixed version:
public class FavoriteClassList
{
public int ID { get; set; }
public string Name { get; set; }
}
public static ObservableCollection<FavoriteClassList> _FavoriteClassList = new ObservableCollection<FavoriteClassList>();
for (int m=1;m<=10;m++)
{
FavoriteClassList objFavoriteClassList = new FavoriteClassList();
objFavoriteClassList.ID = m;
objFavoriteClassList.Name = "Name"+m;
_FavoriteClassList.Add(objFavoriteClassList);
}

Create unique postalcode and country generator

I am working an C# application where I have to add test employee data to a MongoDB collection.
There is a working connection already and some predefined list where the program is going to loop through to insert data. However, I am stuck add the point where I'd have to add an address.
I need a piece of code to create at least 10.000 unique postalcodes without using a library if possible.
using System;
using System.Collections.Generic;
using MongoDB.Driver;
using MongoDB.Bson;
namespace Application
{
class Program
{
public class Employee
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Street { get; set; }
public string Country { get; set; }
public string Postalcode { get; set; }
}
static void Main(string[] args)
{
MongoClient client = new MongoClient();
var server = client.GetServer();
var db = server.GetDatabase("testdb");
var collection = db.GetCollection<Employee>("testcollection");
List<string> names = new List<string>()
{
"John Smith",
"Matthew Williams",
"David Harris",
"Christopher Martin",
"Paul Shark"
};
Random random = new Random();
for (int i = 0; i < 5; i++)
{
int nameIndex = random.Next(0, 5);
int projectIndex = random.Next(0, 3);
int ageIndex = random.Next(18, 67);
string nameValue = names[nameIndex];
Employee employee = new Employee
{
BSN = "BSN" + i,
Name = nameValue,
Age = ageIndex
};
collection.Save(employee);
}
}
}
}
When I test forms I grab Faker.net from Nuget. This will generate random data for everything you need.
The implementation is pretty simple. Going from memory here so your mileage may vary but you get the idea.
var address1 = Faker.address.address1;

Add values to Dictionary<int,class> not all at once

I'm trying to store data in a dictionary where the key is an ID and the values are of a class type. The class properties are not all added at the same time so I haven't used a constructor - unless there is a way to add new values using a constructor at a different times? The code below compiles, but I get a run time error saying the key has already been added.Thanks for the help.
public class Students
{
public string FirstName { get; set; }
public string SurName { get; set; }
public int Age { get; set; }
public double Score { get; set; }
}
public void cmdTEST_Click(object sender, EventArgs e)
{
Dictionary<int, Students> Data = new Dictionary<int, Students>();
Data.Add(5, new Students { FirstName = "Bob" });
Data.Add(5, new Students { Age = 34 }); // run time error - "key already added"
Data.Add(5, new Students { Score = 62 });
// extract data
double Score5 = Data[5].Score;
double Age5 = Data[5].Age;
}
You are adding same key multiple times which is not allowed. You can add all properties at once like below
Dictionary<int, Students> Data = new Dictionary<int, Students>();
Data.Add(5, new Students { FirstName = "Bob", Age = 34, Score = 62 });
And if you want to add values later you can use key to add values
Data.Add(5, new Students { FirstName = "Bob"});
Data[5].Age = 34;
Data[5].Score = 62;

How to parse DbGeometry object into List<T>?

I'm trying to parse a polygon, which is presented as DbGeometry class (from the System.Data.Entity.Spatial) to some List representation, but there were fails.
I've tried:
- to convert it with the method .ToList<>()
- to parse using JSON library in .NET, but have sample code from different websites failed with deserializing DbGeometry
So, right now I'm returning geometry as a string in my Web API application:
If I couldn't find any solution how, to represent it as list of doubles I will have to parse manually it in JavaScript, which way I think is very incorrect and there must be some solution.
I'm using Entity Framework v.6.1.1, which has prepared the next model:
public partial class Buildings
{
public int id { get; set; }
public Nullable<bool> has_holes { get; set; }
public System.Data.Entity.Spatial.DbGeometry polygon_data { get; set; }
public System.Data.Entity.Spatial.DbGeometry position_wgs { get; set; }
public System.Data.Entity.Spatial.DbGeometry position_mercator { get; set; }
public Nullable<int> height { get; set; }
public string street_name { get; set; }
public System.Data.Entity.Spatial.DbGeometry holes_data { get; set; }
public Nullable<double> angle { get; set; }
}
I've shown it, if you want to see a structure of the table from MSSQL CE (which is an embedded db, or LocalDb, another name).
So I want:
System.Data.Entity.Spatial.DbGeometry polygon_data
System.Data.Entity.Spatial.DbGeometry holes_data
Be prepared as lists of doubles, so my question is: How can I parse DbGeometry instance, which holds a collection of points into List<Point>?.
I had similar problem. What I did was, created extension method that parse the given geometry data to points. #Erik Philips also have nice solution though. This is what I came up with.
public static class ExtensionString
{
private static Dictionary<string, string> _replacements = new Dictionary<string, string>();
static ExtensionString()
{
_replacements["LINESTRING"] = "";
_replacements["CIRCLE"] = "";
_replacements["POLYGON"] = "";
_replacements["POINT"] = "";
_replacements["("] = "";
_replacements[")"] = "";
}
public static List<Point> ParseGeometryData(this string s)
{
var points = new List<Point>();
foreach (string to_replace in _replacements.Keys)
{
s = s.Replace(to_replace, _replacements[to_replace]);
}
string[] pointsArray = s.Split(',');
for (int i = 0; i < pointsArray.Length; i++)
{
double[] coordinates = new double[2];
//gets x and y coordinates split by space, trims whitespace at pos 0, converts to double array
coordinates = Array.ConvertAll(pointsArray[i].Remove(0, 1).Split(null), double.Parse);
points.Add(new Point() { X = coordinates[0], Y = coordinates[1] });
}
return points;
}
}
And just use it like this
List<System.Drawing.Point> points = geometryDataStr.ParseGeometryData();
If your Geometry is Valid then you can do:
class Program
{
static void Main(string[] args)
{
DbGeometry test = DbGeometry.FromText("POLYGON((1 1, 1 2, 3 3, 1 1))");
var foo = test.AsText();
var points = new List<Point>();
Console.WriteLine(foo);
if (foo.StartsWith("POLYGON ((")
&& foo.EndsWith("))"))
{
foo = foo.Substring(10, foo.Length - 12);
var rawPoints = foo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (var rawPoint in rawPoints)
{
var splitPoint = rawPoint.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
points.Add(new Point() { X = decimal.Parse(splitPoint[1]), Y = decimal.Parse(splitPoint[0]) });
}
}
foreach (var point in points)
{
Console.WriteLine(point.ToString());
}
Console.ReadKey();
}
}
class Point
{
public decimal X { get; set; }
public decimal Y { get; set; }
public override string ToString()
{
return string.Format("[X={0}],[Y={1}]", X, Y);
}
}
result:
POLYGON ((1 1, 1 2, 3 3, 1 1))
[X=1],[Y=1]
[X=2],[Y=1]
[X=3],[Y=3]
[X=1],[Y=1]

Categories

Resources