开发者

How to match the results back to an array

I have an array of objects. The object has two properties a value and an index.

I use 开发者_如何转开发a linq to entities query with the contains keyword to bring back all results in a table that match up to value.

Now here is the issue... I want to match up the results to the object index...

what is the fastest best way to perform this. I can add properties to the object.

It is almost like I want the query results to return this:

index = 1;
value = "searchkey"
queryvalue = "query value"


From your question I think I can assume that you have the following variables defined:

  • Lookup[] (You look-up array)
  • IEnumerable<Record> (The results returned by your query)

... and the types look roughly like this:

public class Lookup
{
    public int Index { get; set; }
    public int Value { get; set; }
}

public class Record
{
    public int Value { get; set; }
    /* plus other fields */
}

Then you can solve your problem in a couple of ways.

First using an anonymous type:

var matches
    = from r in records
      join l in lookups on r.Value equals l.Value
      group r by l.Index into grs
      select new
      {
          Index = grs.Key,
          Records = grs.ToArray(),
      };

The other two just use standard LINQ GroupBy & ToLookup:

IEnumerable<IGrouping<int, Record>> matches2
    = from r in records
      join l in lookups on r.Value equals l.Value
      group r by l.Index;

ILookup<int, Record[]> matches3
    = matches2.ToLookup(m => m.Key, m => m.ToArray());

Do these solve your problem?


Just a shot in the dark as to what you need, but the LINQ extension methods can handle the index as a second paramter to the lambda functions. IE:

someCollection.Select( (x,i) => new { SomeProperty = x.Property, Index = i } );

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜