I have 2 arrays of different types one is from file and one is from a SQL Database - LINQ to SQL. I'm trying to delete non matching items from my database against items I receive via the file. (I mention this in case there is a more efficient way to do what I'm trying to achieve).
I've drafted up a couple of anonymous arrays to show what I am trying to do:
var a = new[] {
new { code = "A", subid = 1, test = "dunno" }, new { code = "A", subid = 2, test = "dunno" }, new { code = "A", subid = 3, test = "dunno" },
new { code = "B", subid = 1, test = "dunno" }, new { code = "B", subid = 2, test = "dunno" }, new { code = "B", subid = 3, test = "dunno" }
};
var c = new[] {
new { code = "A", subid = 1 }, new { code = "A", subid = 2 },
new { code = "B", subid = 1 }, new { code = "B", subid = 2 }
};
I need it to return the items that do not match e.g. new { code = "A", subid = 3 } and new { code = "B", subid = 3 }
var b = (from items in a
where c.Any(d => d.code == items.code && d.subid != items.subid)
select items);
and
var b = (from items in a
where c.Where(d=> d.code == items.code).Any(d => d.subid != items.subid)
select items);
I've tried these but they just seem to return all the items. How do I do this?
Use Enumerable.Except
var nonMatchingItems = a.Except(c);
Full sample:
var a = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "A", subid = 3 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 },
new { code = "B", subid = 3 }
};
var c = new[] {
new { code = "A", subid = 1 },
new { code = "A", subid = 2 },
new { code = "B", subid = 1 },
new { code = "B", subid = 2 }
};
foreach(vat item in a.Except(c))
Console.WriteLine(item);
// { code = A, subid = 3 }
// { code = B, subid = 3 }
UPDATE (if you have different types, and want to find matches of some set of fields, then use join of sequences, and remove all items from a which matched some items in c:
var matchingItems = from aa in a
join cc in c
on new { aa.code, aa.subid } equals // properties subset
new { cc.code, cc.subid } // same subset
select aa; // select inner item from join
var nonMatchingItems = a.Except(matchingItems);
Related
I'm trying to insert data in a migration using migrationBuilder.InsertData. According to the docs, I should be able to insert multiple rows with multiple columns using InSertData(String, String[], String[], Object[,], String) but I can't seem to format my data properly for the Object[,] values.
The code below is just sample code that I'm using on dotnetfiddle so that I could easier see what my data was looking like.
class MyModel
{
public string name {get; set;}
public bool active {get; set;}
}
public class Program
{
public static void Main()
{
var e = new String[] {"b", "c", "d"};
var x = new List<MyModel>() {
new MyModel {name = "f", active = false},
new MyModel {name = "a", active = false},
new MyModel {name = "b", active = false},
new MyModel {name = "c", active = false},
new MyModel {name = "d", active = false},
new MyModel {name = "e", active = false},
new MyModel {name = "f", active = false},
new MyModel {name = "f", active = false},
new MyModel {name = "f", active = false},
};
var _data = x.Select(a => a.name)
.Distinct()
.OrderBy(a => a)
.Select(a => new object[] {a, e.Contains(a) ? 0 : 1})
.ToArray();
Console.WriteLine(JsonConvert.SerializeObject(_data)); // for testing purposes
Console.WriteLine(_data[1][0]); // b
Console.WriteLine(_data is Array); // true
Console.WriteLine(((Array)_data).Rank == 2); // false
Console.WriteLine(((Array)_data).Rank); // 1
}
}
In my migration file:
migrationBuilder.InsertData(
table:'Model',
columns: new string[] {"name","active"},
columnTypes: new string[] {"string","bit"},
values: _data // This throws an error: The number of values (38) doesn't match the number of columns(2) for the data insertion operation.
)
I have a list lstCollectionInstances which has 4 collection instance,
var lstCollectionInstances = new List<CollectionInstance>
{
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 10, DataType = "D"}
}
},
new CollectionInstance
{
Name = "A",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H1", DataType = "S"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P1", Value = 20, DataType = "D"}
}
},
new CollectionInstance
{
Name = "B",
CollectionProperties = new List<CollectionProperty>
{
new CollectionProperty {Name = "P2", Value = "H2", DataType = "S"}
}
},
};
Now when I filter it based on CollectionProperty data types D it's should give me 2 records, but below code giving me all 4 records, what is missing here?
var X = lstCollectionInstances.Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties.Where(cp => cp.DataType == "D").ToList()
}).ToList();
This one selects all instances with a property of type D.
var result= lstCollectionInstances
.Where(x => x.CollectionProperties.Any(y => y.DataType == "D"))
.ToList();
It is because you're executing Select in each item of lstCollectionInstances and Where in CollectionProperties. It will return 4 items which 2 of them have empty CollectionProperties. You should execute Where first like:
var X = lstCollectionInstances.Where(a => a.CollectionProperties.Any(cp => cp.DataType == "D")).Select(x => new CollectionInstance
{
Name = x.Name,
CollectionProperties = x.CollectionProperties
}).ToList();
I'm writing a tag search in C# MVC, but I'm only able to get all the results that have one of the words. - The output should be only where all the input words matches, and exclude if e.g. 2 words are in the input, but only one of them matches.
My code so far:
List<String> list = Request["tags"].Split(' ').ToList();
KDBEntities q = new KDBEntities();
var query = (from tag in q.KDB_tags join question in q.KDB_questions on tag.question_id equals question.id where list.Any(x => x.Equals(tag.tag)) select question);
var Rquery = query.GroupBy(x => x.id).Select(grp => grp.FirstOrDefault()).ToList();
return View(Rquery);
I've been trying to figure this out for quite a while, but with no luck.
Hope this makes sense, and any of you can help me.
Tags list:
List<TagObj> tags = new List<TagObj>()
{
new TagObj() { Id = 1, QuestionId = 1, Tag = "news" },
new TagObj() { Id = 2, QuestionId = 1, Tag = "sports" },
new TagObj() { Id = 3, QuestionId = 1, Tag = "famous" },
new TagObj() { Id = 4, QuestionId = 2, Tag = "news" },
new TagObj() { Id = 5, QuestionId = 2, Tag = "sports" },
new TagObj() { Id = 6, QuestionId = 3, Tag = "news" },
new TagObj() { Id = 7, QuestionId = 4, Tag = "funny" },
};
Questions list:
List<QuestionObj> questions = new List<QuestionObj>()
{
new QuestionObj(){ QuestionId = 1, Question = "Whats up footballers?" },
new QuestionObj(){ QuestionId = 2, Question = "These are famous news?" },
new QuestionObj(){ QuestionId = 3, Question = "Read all about it?" },
new QuestionObj(){ QuestionId = 4, Question = "You know whats funny?" }
};
These are incoming tags from the request:
var incomingTags = new List<string>() { "news", "sports" };
These are the queries:
var query = from t in tags
join q in questions on t.QuestionId equals q.QuestionId
where incomingTags.Contains(t.Tag)
select new { question = q, tag = t };
var result = query.
GroupBy(g => g.question.QuestionId).
Where(g => g.ToList().Select(l => l.tag.Tag).SequenceEqual(incomingTags)).
Select(s => s.First().question).ToList();
How can I transform this dictionary to list
var dict = new Dictionary<string, List<string>>();
dict.Add("1", new List<string>() { "a", "b" });
dict.Add("2", new List<string>() { "a", "c" });
I'm expecting this output
List<dynamic> = new List<dynamic>()
{
new { id = "1", value = "a" }
new { id = "1", value = "a" }
new { id = "2", value = "a" }
new { id = "2", value = "a" }
}
I've tried this but can't get the values of the nested collections:
dict.Select(c => new { id=c.Key, value= c.Value })
Use SelectMany to return multiple items for each KeyValuePair. Then for each pair use Select on the Value:
var result = dict.SelectMany(pair => pair.Value.Select(item =>
new { id = pair.Key, value = item }));
Result:
I'm trying to create nested group with dynamic query.
Following are my collection of data
var invoices = new List < Purchase > () {
new Purchase() {
Id = 1, Customer = "a", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 2, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 3, Customer = "a", Date = DateTime.Parse("1/2/2009")
}, new Purchase() {
Id = 4, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 5, Customer = "b", Date = DateTime.Parse("1/1/2009")
}, new Purchase() {
Id = 6, Customer = "b", Date = DateTime.Parse("1/2/2009")
}
};
This linq query is returning the desired result.
var tree = invoices.GroupBy(x => x.Date).Select(x => new
{
Key = x.Key,
Items = x.GroupBy(y => y.Customer).Select(y => new
{
Key = y.Key,
Items = y
})
}).ToList();
Below is the output of the above linq query
But I just need to group different columns in different order.
So that I try to create dynamic linq query. But my code block result not same as my previous linq query.
var groupedInvoiceItems = invoices.AsQueryable().GroupBy("new (Date, Customer)", "it");
You could do this with Generics. Just Pass in your Lambda to a generic method.
Something like:
private IEnumerable<PurchaseGrp> BuildList<TSource>(IQueryable<TSource> allRecords,
Func<TSource, string> selector)
{
var result = allRecords.GroupBy(x = > x.selector(x));
return result;
}
The return type could be a new Grouped type PurchaseGrp or the same as your source (Purchase).