E
Ethan Strauss
Hi,
I am pretty new to Linq and I am not quite sure when it is best to use it
and when other methods might be preferable.
For example, I need to create a list of Sample objects which I then access
by the SampleName property of each sample.
The way I have generally done this would be with a Dictionary<string,
Sample>, but instead I can use a List<Sample> and access using linq. I don't
know which would be preferable. Any thoughts?
I have example code below.
Thanks!
Ethan
With Dictionary
Dictionary<string, Sample> samples = new Dictionary<string, Sample>();
while (reader.Peek() > 0)
{
string[] line = reader.ReadLine().Split('\t');
if (samples.ContainsKey(line[1]))
{
samples[line[1]].AddDyeChannel(line);
}
else
{
samples.Add(line[1], new Sample(line));
}
}
With List and Linq
List<Sample> samples = new List<Sample>();
while (reader.Peek() > 0)
{
string[] line = reader.ReadLine().Split('\t');
var thisSample = from samp in samples
where samp.SampleName == line[1]
select samp;
switch (samples.Count)
{
case 0:
{
samples.Add(new Sample(line));
break;
}
case 1:
{
samples.First().AddDyeChannel(line);
break;
}
default:
{
throw new
ArgumentException(string.Format("Sample {0} was in the list more than once.",
line[1]));
}
}
}
I am pretty new to Linq and I am not quite sure when it is best to use it
and when other methods might be preferable.
For example, I need to create a list of Sample objects which I then access
by the SampleName property of each sample.
The way I have generally done this would be with a Dictionary<string,
Sample>, but instead I can use a List<Sample> and access using linq. I don't
know which would be preferable. Any thoughts?
I have example code below.
Thanks!
Ethan
With Dictionary
Dictionary<string, Sample> samples = new Dictionary<string, Sample>();
while (reader.Peek() > 0)
{
string[] line = reader.ReadLine().Split('\t');
if (samples.ContainsKey(line[1]))
{
samples[line[1]].AddDyeChannel(line);
}
else
{
samples.Add(line[1], new Sample(line));
}
}
With List and Linq
List<Sample> samples = new List<Sample>();
while (reader.Peek() > 0)
{
string[] line = reader.ReadLine().Split('\t');
var thisSample = from samp in samples
where samp.SampleName == line[1]
select samp;
switch (samples.Count)
{
case 0:
{
samples.Add(new Sample(line));
break;
}
case 1:
{
samples.First().AddDyeChannel(line);
break;
}
default:
{
throw new
ArgumentException(string.Format("Sample {0} was in the list more than once.",
line[1]));
}
}
}