我创建了一个快速控制台应用程序,它创建了 10000 个年轻人和 10000 个老年人并将他们添加到两个单独的列表中。然后我执行一些查询以获取基于个性的信息。
class Program
{
static void Main(string[] args)
{
private Random random = new Random();
private List<Person> youngerPersons = new List<Person>();
private List<Person> olderPersons = new List<Person>();
private long samePersonalityMatches = 0;
for (int i = 0; i < 10000; i++)
{
youngerPersons.Add(new Person(RandomString(10), DateTime.Now.ToString(), RandomString(4), random.Next(10, 50),(Person.PersonalityType)random.Next(0, 4), i));
}
for (int i = 0; i < 10000; i++)
{
olderPersons.Add(new Person(RandomString(10), DateTime.Now.ToString(), RandomString(4), random.Next(51, 120),(Person.PersonalityType)random.Next(0, 4), i));
}
//Example query 1
foreach (Person person in youngerPersons.Where(w => w.Id > 4567 && w.Age > 70))
{
Console.WriteLine(person.Id);
}
//Example query 2
foreach (Person person in youngerPersons)
{
foreach (Person olderPerson in olderPersons)
{
if (person.Personality == olderPerson.Personality)
{
samePersonalityMatches++;
}
}
}
Console.WriteLine("Number of matches: " + samePersonalityMatches);
}
private static Random random = new Random((int)DateTime.Now.Ticks);
private static string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
}
internal class Person
{
public enum PersonalityType
{
Funny = 0,
Boring = 1,
Serious = 2,
Grumpy = 3,
Normal = 4
}
public Person(string name, string dateofbirth, string nickname, int age, PersonalityType personalityType, int id)
{
this.Name = name;
this.Dateofbirth = dateofbirth;
this.Nickname = nickname;
this.Age = age;
this.Id = id;
this.Personality = personalityType;
}
public string Name { get; set; }
public string Dateofbirth { get; set; }
public string Nickname { get; set; }
public int Age { get; set; }
public int Id { get; set; }
public PersonalityType Personality { get; set; }
}
基本上,我想了解最佳实践,以从我放入代码中的两个示例查询中获得最大性能。我已经阅读了一些有关使用 intersect 的性能相关材料,但我不确定哪个以及何时最适合使用以获得最佳性能。这些列表有点 OTT(大小明智),但它使示例 2 运行起来更有趣。