> I have tab-delimited data ( 300 lines, 2 pieces of data per line) that
> is in a string (it came from a network stream, not a file or anything
[quoted text clipped - 3 lines]
> entities, mapping the first data element in a line to the first
> property, etc?
Well, LINQ operates on things that implement IEnumerable. So the first
thing you need to do is convert your string to something that's
enumerable. Then you can use LINQ to create a query from that result that
returns instances of your class based on the data in each line.
I've posted below an example of a very simple program that does this. If
it's not the sort of thing you're looking for, you will probably want to
rephrase your question so that it's more specific.
By the way, I'm kind of new at this LINQ stuff. I'm hoping that one of
the experts will point out some ways to clean up my code a bit (I'm
especially skeptical of my use of the lambda expression, since with two
statements in the method I'm hard-pressed to see how that syntax is better
than an anonymous method :) ).
Pete
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace TestLinqFromString
{
class Program
{
class Record
{
public readonly string field1;
public readonly string field2;
public Record(string field1, string field2)
{
this.field1 = field1;
this.field2 = field2;
}
}
static void Main(string[] args)
{
string strInput =
"A field1\tA field2\r\n" +
"B field1\tB field2\r\n" +
"C field1\tC field2";
IEnumerable<Record> query = strInput.Split(new string[]
{ "\r\n" }, StringSplitOptions.None)
.Select(str =>
{
string[] strFields = str.Split('\t');
return new Record(strFields[0], strFields[1]);
});
foreach (Record rec in query)
{
Console.WriteLine(rec.field1 + ", " + rec.field2);
}
Console.ReadLine();
}
}
}
coconet - 08 Apr 2008 15:26 GMT
Thanks a lot, you got me started in the right direction. Time for a
new LINQ post with a new question... :)
Marc Gravell - 08 Apr 2008 15:35 GMT
> I'm especially skeptical of my use of the lambda expression
If I have the language the right way around, it *isn't* a lambda
expression; it is a lambda statement - and indeed, it is exactly
identical to anonymous method. The real benefit of lambda expressions
comes when you are talking to an alternative data-source, using an
Exression<Foo> (for Foo some delegate-type such as Func<T>) - i.e.
LINQ-to-SQL, EF, etc - as an expression can be inspected to form a query
(i.e. a cut-down SELECT statament).
In this scenario, it isn't going to make any difference, so whatever
works and is readable...
Marc