How to split into sublists using LINQ? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Split List into Sublists with LINQ
I'm looking for some way to split an enumerable into three enumerables using LINQ, such that each successive item in the input is in the next sublist in in the sequence. So input
{"a", "b", "c", "d", "e", "f", "g", "h"}
would result in
{"a", "d", "g"}, {"b", "e", "h"}, {"c", "f"}
I've done it this way but I'm sure there must be a way to express this more elegantly using LINQ.
var input = new List<string> {"a", "b", "c", "d", "e", "f", "g", "h"};
var list = new List<string>[3];
for (int i = 0; i < list.Length; i++)
list[i] = new List<string>();
int column = 0;
foreach (string letter in input)
{
list[column++].Add(letter);
if (column > 2) column = 0;
}

This is what you are looking for:
(Splits by columns) Modified based on the previous posts
The key difference is in the group by, using mod instead of division.
Also I made it generic so it gives you back the proper type (as opposed to "object typed" code). You can just use type inference with generics.
public static IEnumerable<IEnumerable<T>> SplitColumn<T>( IEnumerable<T> source ) {
return source
.Select( ( x, i ) => new { Index = i, Value = x } )
.GroupBy( x => x.Index % 3 )
.Select( x => x.Select( v => v.Value ).ToList() )
.ToList();
}

Related

Intersection of Two lists with index using lambda Expressions

I am trying to make a dictionary that contains the index and matched elements of two sequences.
for example:-
List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
List<string> B = new List<string> { "a", "d", "e", "f" };
Now I want to build a dictionary that looks like this.
// Expected Output:-
// { "a" , 0 }
// { "d" , 3 }
// { "e" , 4 }
// { "f" , 5 }
where the first entry in dictionary is the common element in both the lists and second one is the index of that in the first list(A).
Not sure on how to phrase a Lambda Expression to do that.
Do to so, for each element in B use IndexOf in the A collection. Then use ToDictionary to convert it to the dictionary form you wanted
List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
List<string> B = new List<string> { "a", "d", "e", "f" };
var result = B.Select(item => new { item, Position = A.IndexOf(item) })
.ToDictionary(key => key.item, value => value.Position);
Keep in mind that the items in B must be unique for it to not fail on KeyAlreadyExists. In that case:
var result = B.Distinct()
.Select(item => new { item, Position = A.IndexOf(item) })
.ToDictionary(key => key.item, value => value.Position);
If you do not want results for items that weren't found:
var result = B.Distinct()
.Select(item => new { item, Position = A.IndexOf(item) })
.Where(item => item.Position != -1
.ToDictionary(key => key.item, value => value.Position);
This should do it:
List<string> A = new List<string>{"a","b","c","d","e","f","g"};
List<string> B = new List<string>{"a","d","e","f"};
var result = B.ToDictionary(k => k, v => A.IndexOf(b)});
try this:
List<string> A = new List<string> { "a", "b", "c", "d", "e", "f", "g" };
List<string> B = new List<string> { "a", "d", "e", "f" };
Dictionary<string, int> result = B.ToDictionary(x => x, x => A.IndexOf(x));

Identify subsets of root data in a list of trees

I have following structure:
Node
{
List<String> rootData;
List<Node> Children;
}
and a collection as
List<Node> lstOfTrees
the first Structure holds some words on rootData, (List of node is not really important here) and the collection lstOfTrees contains the the trees.
Problem is:
In lstOfTrees, there are multiple trees. Some of the trees have subset of rootData of other trees (possibly, not necessarily). I want to keep the tree having super-set of other rootData(s) in lstOfTrees (subset should be ignored).
example:
assuming, lstOfTrees contain the trees as
1: {rootData: A, B, C, D}
2: {rootData: E, F, G}
3: {rootData: G, H}
4: {rootData: J, A, C}
5: {rootData: D, Z}
the final answer I need, should be in a new list containing:
1: {rootData: A, B, C, D}
2: {rootData: E, F, G}
Can this be done using LINQ and TPL (or the more effecient way) ? I want it to be efficient and correct.
EDIT:
should the following code work correctly in all cases or am I missing something??
lstOfTrees.Add(new node());
lstOfTrees[0].rootData = new List<string> {"A", "B", "C", "D"};
lstOfTrees.Add(new node());
lstOfTrees[1].rootData = new List<string> {"E", "F", "G"};
lstOfTrees.Add(new node());
lstOfTrees[2].rootData = new List<string> {"G", "H"};
lstOfTrees.Add(new node());
lstOfTrees[3].rootData = new List<string> {"J", "A", "C"};
lstOfTrees.Add(new node());
lstOfTrees[4].rootData = new List<string> {"D", "Z"};
Dictionary<int,node> dictOfTrees_indexToNode = Enumerable.Range(0, lstOfTrees.Count).ToDictionary(x=>x,x => lstOfTrees[x]);
List<int> notToInclude = new List<int>();
for (int i = 0; i < lstOfTrees.Count; i++)
{
for (int j = 0; j < lstOfTrees.Count; j++)
{
if (j != i)
{
if (!lstOfTrees[j].Equals(lstOfTrees[i]))
{
if (lstOfTrees[j].rootData.Join(lstOfTrees[i].rootData, root => root, innerRoot => innerRoot,
(root, innerRoot) => 1).Any())
{
bool test = (lstOfTrees[j].rootData.Count > lstOfTrees[i].rootData.Count);
notToInclude.Add(test ? i : j);
}
}
}
}
}
List<node> finalList = new List<node>();
finalList.AddRange(lstOfTrees.Except(notToInclude.Select(s=>dictOfTrees_indexToNode[s])));
Also, Can I improve from this?
I've simplified the case a little bit for testing to just searching through the list of list of strings, which should be the same thing that you're doing after a small middle step:
var list = lstOfTrees.Select(x => new HashSet<string>(x.rootData)).ToList();
Also, it's quite possible that it would be better to use sets here, at least I don't see any duplicates in the example data, and that's the second change.
Using sets here is quite important, so if data can - in fact - be duplicated in the lists, then the whole solution would have to change.
Here's the result:
var list = new List<List<string>> {
new List<string> {"A", "B", "C", "D"},
new List<string> {"E", "F", "G"},
new List<string> {"G", "H"},
new List<string> {"J", "A", "C"},
new List<string> {"D", "Z"}};
var sets = list.Select(x => new HashSet<string>(x)).ToList();
var result = sets.Select(x => sets.Where(y => x.Overlaps(y)) // You are looking not for 'subsets', but overlapping sets
.OrderByDescending(y => y.Count)
.FirstOrDefault())
.Distinct();
This returns IEnumerable<HashSet<string>>:
{"A", "B", "C", "D"}, {"E", "F", "G"}
Tested in LINQPad :)

Create unique doubles and triplets from collection

I have a Collection (List) of items (String). Number of items in this collection will always be between 0 to 9.
I need to create all combinations of pairs and triples from this collection.
Position of item in double or triplet does not matter. So {1,2} is equal to {2,1}.
How can i achieve this? Maybe there is some nice way to do this via LINQ?
In the code below I generate all unique doubles and triplets using linq. I use the fact that strings have a total ordering.
This generates all doubles:
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
var combinations =
from a in items
from b in items
where a.CompareTo(b) < 0
orderby a, b
select new { A = a, B = b };
foreach(var pair in combinations)
Console.WriteLine("({0}, {1})", pair.A, pair.B);
This generates all triplets:
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
var combinations =
from a in items
from b in items
from c in items
where a.CompareTo(b) < 0 && b.CompareTo(c) < 0
orderby a, b, c
select new { A = a, B = b, C = c };
foreach(var triplet in combinations)
Console.WriteLine("({0}, {1}, {2})", triplet.A, triplet.B, triplet.C);
Update: There is a generic solution to create all unique subsets of a specific length, and still use linq. However, you need a returntype that can contain the subset. I created a simple class LinkedNode, because to me this feels most natural in combination with linq:
void Main()
{
string[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
foreach(var combination in CreateCombinations(items, 5))
Console.WriteLine("({0})", combination.ToString());
}
private static IEnumerable<LinkedNode> CreateCombinations(string[] items, int length)
{
if(length == 1)
return items.Select(item => new LinkedNode { Value = item, Next = null });
return from a in items
from b in CreateCombinations(items, length - 1)
where a.CompareTo(b.Value) < 0
orderby a, b.Value
select new LinkedNode<T> { Value = a, Next = b };
}
public class LinkedNode
{
public string Value { get; set; }
public LinkedNode Next { get; set; }
public override string ToString()
{
return (this.Next == null) ? Value : Value + ", " + Next.ToString();
}
}
It should be easy to implement IEnumerable<string> on the class LinkedNode, or otherwise convert the LinkedNodes to a List<string> or HashSet<string>. Note that you can remove the line orderby a, b.Value if the order is not important.

C# : How to get running combination from two List<String> based on a master list

Dear all , this is something like my previous question How to get moving combination from two List<String> in C#?
I'm having a masterlist and two childlist like below
List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
List<String> ListOne = new List<string> { "A", "B", "C" };
List<String> ListTwo = new List<String> { "B", "D" };
I just need to get the running combination from the above list for that i'm using like(previous question's answer(Thanks Danny Chen))
List<String> Result = new List<string>();
Result = ListOne.SelectMany((a, indexA) => ListTwo
.Where((b, indexB) => ListTwo
.Contains(a) ? !b.Equals(a) && indexB > indexA :
!b.Equals(a)).Select(b => string.Format("{0}-{1}", a, b))).ToList();
so the Result list will contain
"A-B"
"A-D"
"B-D"
"C-B"
"C-D"
Now my problem is the sorting issue
In the above result the fourth entry is C-B but it should be B-C. Because in the MasterList the C is after B.
How to do this in my existing linq .
Please help me to do this.
Not really clear on the exact requirement here, so does the MasterList dictate which of the two items should appear first? What about the order of the X1-X2 list? i.e. should B-C appear before B-D because C appears before D in the MasterList?
Anyway, here's something that produces the result you've asked for so far:
List<String> MasterList = new List<string> { "A", "B", "C", "D", "E" };
List<String> ListOne = new List<string> { "A", "B", "C" };
List<String> ListTwo = new List<String> { "B", "D" };
ListOne.SelectMany(i =>
ListTwo.Where(i2 => i != i2)
.Select(i2 =>
{
if (MasterList.IndexOf(i) < MasterList.IndexOf(i2))
return string.Format("{0}-{1}", i, i2);
else
return string.Format("{0}-{1}", i2, i);
}
));
outputs:
A-B
A-D
B-D
B-C
C-D

LINQ expression for shortest common prefix

Can anyone help me with a nice LINQ expression for transforming a list of strings in another list containing only the shortest distinct common prefixes for the strings? The delimiter for prefixes is ..
Example: ["A", "A.B.D", "A", "A.B","E","F.E", "F","B.C"]
Goes to: ["A", "E", "F", "B.C"]
Removed:
"A.B.D" and "A.B" because the prefix "A" is already in the list
"A" because is duplicate
"F.E" because "F" already in list
Thanks!
Here you go:
from set in
(from item in list select item.Split('.')).GroupBy(x => x[0])
select
set.First()
.TakeWhile((part, index) => set.All(x => x.Length > index && x[index].Equals(part)))
.Aggregate((x, y) => String.Format("{0}.{1}", x, y));
By way of explanation:
First, we split all the strings by '.' and group by their first token.
Then, we look at the first element of each grouping, and we take parts from it while every element of that group continues to match (TakeWhile).
Then, we take all those parts and recompose them with the Aggregate(String.Format).
var items = new[] { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = items
.OrderBy(s => s.Length)
.Distinct()
.ToLookup(s => s.Substring(0, 1))
.Select(g => g.First());
Order the items by their length, call distinct to remove duplicates, convert to groupings based on the first character, and select the first item in each group.
Yields:
"A", "E", "F", "B.C"
Edit: You probably don't even need Distinct as your selecting the first item in each group anyway, so it's really redundant.
EDIT: thanks to the comments for pointing out a bug in my earlier approach.
To get around that shortcoming this query should work:
var list = new List<string> { "A.B.D", "A", "A.B","E","F.E", "F","B.C", "B.C.D" };
var result = list.OrderBy(s => s)
.GroupBy(s => s[0])
.Select(g => g.First());
foreach (var s in result)
{
Console.WriteLine(s);
}
Incorrect approach:
The following query will group each string by the first character. Next, if the group count has more than one item the key is selected, otherwise the single item is selected.
var list = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = list.GroupBy(s => s[0])
.Select(g => g.Count() > 1 ? g.Key.ToString() : g.Single());
foreach (var s in result)
{
Console.WriteLine(s);
}
Nailed it - assuming that if the source list contains "Q.X" & "Q.Y" then the result should contain "Q".
var source = new []
{
"A", "A.B.D", "A",
"A.B", "E", "F.E",
"F", "B.C",
"Q.X", "Q.Y",
"D.A.A", "D.A.B",
};
Func<string, int> startsWithCount =
s => source.Where(x => x.StartsWith(s)).Count();
var results =
(from x in source.Distinct()
let xx = x.Split('.')
let splits = Enumerable
.Range(1, xx.Length)
.Select(n => String.Join(".", xx.Take(n)))
let first = startsWithCount(splits.First())
select splits
.Where(s => startsWithCount(s) == first)
.Last()
).Distinct();
// results == ["A", "E", "F", "B.C", "Q", "D.A"]
string[] source = {"A", "A.B", "A.B.D", "B.C", "B.C.D", "B.D", "E", "F", "F.E"};
var result =
source.Distinct()
.Select(str => str.Split('.'))
.GroupBy(arr => arr[0])
.Select(g =>
{
return string.Join(".",
g.Aggregate((arr1, arr2) =>
{
return arr1.TakeWhile((str, index) => index < arr2.Length
&& str.Equals(arr2[index]))
.ToArray();
}));
});
Steps:
(1) Remove duplicated elements by Distinct()
(2) Split each element to an array, also get ready to be grouped
(3) Group those arrays by the first string in the array
(4) For each group, create one common prefix by aggregating all arrays in the group. The logic for aggregating is that for two arrays arr1 and arr2, take the elements in arr1 until (1)out of bounds (2) corresponding element in arr2 is different
Note: I add two return statements in the code, to make it look cleaner. It can be shorter if remove return and its {} brackets.
How about:
var possible = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var shortest = possible.Distinct().Where(x => possible.Distinct().Where(y => !y.Equals(x) && x.StartsWith(y)).Count() == 0).ToList();
It checks the list against itself excluding items that are equal and any items that starts with any of the other items. I'm not sure about the effeciency though :)
I think it might be hard to solve with one single nice looking linq expression so I wrote a recursive function using linq that solves the problem:
class Program
{
static void Main(string[] args)
{
var input = new string[] { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C", "B.C.D", "B.E" };
var output = FilterFunc(input);
foreach (var str in output)
Console.WriteLine(str);
Console.ReadLine();
}
static string[] FilterFunc(string[] input)
{
if (input.Length <= 1)
return input;
else
{
var firstElem = input[0];
var indexNr = firstElem.Length;
var maxFilteredElems = 0;
for (int i = firstElem.Length; i > 0; i--)
{
var numberOfFilteredElems = input.Where(x => x.StartsWith(firstElem.Substring(0, i))).Count();
if (numberOfFilteredElems > maxFilteredElems)
{
maxFilteredElems = numberOfFilteredElems;
indexNr = i;
}
}
var prefix = firstElem.Substring(0, indexNr);
var recursiveResult = FilterFunc(input.Where(x => !x.StartsWith(prefix)).ToArray());
var result = recursiveResult.ToList();
prefix = prefix.EndsWith(".") ? prefix.Substring(0, prefix.Length - 1) : prefix;
result.Insert(0, prefix);
return result.ToArray();
}
}
}
The code could probably be more effective and more organized but don't have time for that now. I think the other solutions are wrong so far, so that's why you get my longer one. I think you need to solve it recursively to be sure to get the shortest list.
My attempt, loop through items removing anything prefixed with another item.
static void Run()
{
var list = new string[] {"A", "A.B.D", "A",
"A.B", "E", "F.E",
"F", "B.C",
"Q.X", "Q.Y",
"D.A.A", "D.A.B"
};
int size = 0;
var prefixList = new string[list.Length];
Array.Copy(list, prefixList, list.Length);
for (int i = 0; i < list.Length; i++)
prefixList
= prefixList
.Where(c => !c.StartsWith(list[i]) || c == list[i])
.Distinct()
.ToArray();
foreach (string s in prefixList)
Console.WriteLine(s);
Console.ReadLine();
}
var list = new[] { "A.B.D", "A", "E", "A.B", "F", "F.E", "B.C.D", "B.C" };
var result = from s in list
group s by s.Split('.').First() into g
select LongestCommonPrefix(g);
foreach (var s in result)
{
Console.WriteLine(s);
}
Output:
A
E
F
B.C
Method to find longest common prefix from here (replace / with .).
My understanding of the question says a list containing both "B.C" and "B.E" but no "B" would get both "B.C" and "B.E".
string[] items = { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
char delimiter = '.';
var result = (from item in items.Distinct()
where !items.Any(other => item.StartsWith(other + delimiter))
select item).ToArray();
foreach (var item in result)
{
Console.WriteLine(item);
}
output
A
E
F
B.C
also works with multi-character prefixes
string[] items =
{
"Alpha",
"Alpha.Beta.Delta",
"Alpha",
"Alpha.Beta",
"Echo",
"Foxtrot.Echo",
"Foxtrot",
"Baker.Charlie"
};
gets
Alpha
Echo
Foxtrot
Baker.Charlie
If I strictly stick to the definition that dave provided, the answer is easier than it seems:
remove duplicates => distinct
remove any item that starts with any other item in the list
so we get:
from item in items.Distinct()
where !items.Any(other => other != item && item.StartsWith(other + '.'))
select item;
For the B.C and B.D question, this works as specified: Neither one includes the other, so none of the removing conditions mentioned by dave is triggered.
I admit that there might be more exciting anwers, but I'm afraid that's just not in the question ;)
Update: added delimiter to where clause in order to account for multi-char words. thanks svick!
var list = new List<string> { "A", "A.B.D", "A", "A.B", "E", "F.E", "F", "B.C" };
var result = (list.Select(a => a.Split('.').First())).Distinct();

Categories

Resources