Projection of dis-joint sets in LINQ
I have two string arrays ( I will not use it anywhere as it is not a good logic,this is for my learning purpose).
string[] names = new[] { "Joss", "Moss", "Kepler" };
string[] emails 开发者_StackOverflow= new[] { "Moss@gmail", "Kepler@gmail", "Joss@gmail" };
How to use LINQ so as to make key value pairs like
{"Joss","Joss@gmail"} ,{"Moss","Moss@gmail"} , {"Kepler","Kepler@gmail"}
- email ids are shuffled in string array emails[]
- consider both string arrays keep unique name and unique email ids (their name as email ids).
How to use Join to project the result i want?
var JoinDemo = from grpname in names
join
grpmails in emails
on grpname ????????
With the constraints you defined this should do the job:
var q = from name in names
join email in emails on name equals email.Remove(email.IndexOf('@'))
select new
{
Name = name,
Email = email
};
Sounds like you want the Zip
operator from .NET 4.0. If you can't wait that long, you can use the implementation in MoreLINQ.
I'm not sure what you mean about the shuffling though... do you really want a random pairing? If so, it's probably easiest to shuffle one array first and then do the zip.
This is the Zip
operation which is not available in .NET 3.5 BCL out of the box.
If you have two arrays (won't work for generic IEnumerable<T>
) of same length, you can use:
var zippedArrays = Enumerable.Range(0, Math.Min(a.Length, b.Length))
.Select(i => new { Name = a[i], Email = b[i] })
.ToList();
精彩评论