How to resolve variable in Linq Query c#? - c#

I have the below dynamic array
dynamic[] queueList = await queueInfo.Run.GetData<dynamic[]>(Name);
I want to get the unique values present in ImportTableName field. So, after some search I found this,
var distNames = queueList.Select(o => new {o.ImportTableName }).Distinct();
which works as expected.
But I don't want to hard code the fieldname "ImportTableName". So tried doing something like this
dynamic[] queueList = await queueInfo.Run.GetData<dynamic[]>(Name);
string tableName = "ImportTableName"
var distNames = queueList.Select(o => new {o.tableName }).Distinct();
But it doesn't work, result is just NULL. Can someone help me to achieve this ?

As it is array of JObject, which has indexer, you can apply it to each element to get value of desired field:
var distNames = queueList.Select(x => x[tableName]).Distinct().ToList();

My solution is:
dynamic[] queueList = new dynamic[]{new { id = 1, ImportTableName = "Data"}};
string propName = "ImportTableName";
var distNames = queueList.Select(d => d.GetType().GetProperty(propName).GetValue(d, null)).Distinct();
It returns as expected "Data".

Related

Mongodb C# driver throwing Element Name '_t' is not valid on UpdateOneAsync

I am getting MongoDb.Bson.SerializationException: 'Element name '_t' is not valid.
I read all posts online that appear to be similar issue at first, however, in those posts, element name is specified, here, i am only getting '_t' even by trying different class objects.
var database = AppConfig.client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("testcollection");
var filter = Builders<Student>.Filter.Eq(g => g.Name, "oldName");
var update = Builders<Student>.Update.Set(g => g.Name, "NewName");
var updateResult = await collection.UpdateOneAsync(filter.ToBsonDocument(), update.ToBsonDocument());
Also, for all examples i have seen online for UpdateOneAsync function, filter and update below do NOT need to be BSON documents, however, my code won't compile unless I do .ToBSONDocument() as above.
var updateResult = await collection.UpdateOneAsync(filter, update);
My class is minimal:
public class Student
{
[BsonElement("Name")]
public string Name { get; set; }
[BsonElement("Age")]
public int Age { get; set; }
}
Can someone please help figure out what is wrong with above?
Update: How to use render for Update.Set
var registry = BsonSerializer.SerializerRegistry;
var serializer = registry.GetSerializer<Student>();
var filter = Builders<Student>.Filter.Eq(g=> g.Name, "NewName").Render(serializer, registry);
//I think update syntax is not correct.
var update = Builders<Student>.Update.Set(g => g.Name, "Changed").Render(serializer, registry);
//update is throwing error:cannot convert from Mongodb.bson.bsonvalue to mongodb.Driver.updatedefinition<MongoDB.Bson.BsonDocument
var updateResult = await collection.UpdateOneAsync(filter, update);
it's impossible to use ToBsonDocument as you did. The easiest fix is using not typed builders:
var filter = Builders<BsonDocument>.Filter.Eq("name", "oldName");
If you want to use typed builder, you should call Render as below:
var registry = BsonSerializer.SerializerRegistry;
var serializer = registry.GetSerializer<Student>();
var filter = Builders<Student>.Filter.Eq(e=>e.Name, "oldName").Render(serializer, registry);

Gremlin .Net, filter vertices by property containing a value

I need to filter vertices in Azure Cosmos Graph DB by a property containing a value, I tried the code below but I am getting an error says (Unable to find any method 'filter')
var g = client.CreateTraversalSource();
var p = new P("containing", text);
var query = g.V().Filter(p).Range<Vertex>(page, pageSize);
var result = await client.ExcuteAsync<IEnumerable<Vertex>>(query);
Any idea how to achieve this?
This might help someone else, I managed to figure it out with some help of a friend:
var p = new P("containing", text);
var query = g.V().has("propertyName", p).Range<Vertex>(page, pageSize);
var result = await client.ExecuteAsync<IEnumerable<Vertext>>(query);
In case anyone is still looking into this, there's predefined predicate values that can be used as string filters in the class TextP.
The above can be accomplished with the following:
var query = g.V().has("propertyName", TextP.Containing(text)).Range<Vertex>(page, pageSize);
var result = await client.ExecuteAsync<IEnumerable<Vertext>>(query);

how can i do json format get a value?

hello this my json value
How can I get a value ?
"a195cc41-4b37-4192-8949-86ae109cfa80,{\"UserID\":2,\"CurrentSessionID\":\"746076a0-6ab9-415a-849a-2755837981bb\",\"Name\":\"SERDAR\",\"Surname\":\"SENGUL\",\"Email\":null,\"Password\":null,\"RememberMe\":false,\"IsActive\":false,\"IsDeleted\":false,\"CreateDate\":\"2015-01-17T09:15:03.6339968+02:00\"},17.01.2015 09:15:03"
var id = clientAuth.Split(',')[0] > it's working (773484c2-5730-4cfa-a17e-2eb041e8c225)
var date = clientAuth.Split(',')[11] > it's working (24.01.2015)
but I can not take get usermodel a value
that comes
var UserID = clientAuth.Split(',')[1] {\"UserID\":2"
var name = clientAuth.Split(',')[2] {\"Surname\":SENGUL"
var createDate = clientAuth.Split(',')[2] "\"CreateDate\":\"2015-01-17T08:44:30.1681286+02:00\"}"
If I understand your questions, you will need to do this:
var firstComma = rawData.indexOf(',');
var lastComma = rawData.lastIndexOf(',');
var jsonString = rawData.slice(firstComma+1,lastComma-firstComma);
var obj = JSON.parse(jsonString);
and then you can refer to the properties of the object like:
var createdate = obj.CreateDate;
var surname = obj.Surname;
Good Luck.
EDIT: You can also use regular expressions to find the '{..}' string, if you prefer.
1.It's not a valid json.
2.Use Json.net for parsing json's in you C# code:
YourObject obj = JsonConvert.DeserializeObject<YourObject>(json);

Building a Dynamic Linq Query using Equals and an Array

I have been trying to solve the syntax for a dynamic linq query that is needed in my application.
I have a dynamic query that the where clause needs to be specified to either
GuidPrimaryKey is contained in a list of Guid OR
GuidPrimaryKey is equal to an item in a list of Guid (using some type of for-loop)
I have a Guid[] populated with over 5,000 keys. My Query is set up as
If I do this (as a test) it is successful
data = data.where("GuidPrimaryKey.Equals(#0)",array[0]);
as well as
data = data.where("GuidPrimaryKey.Equals(#0) OR GuidPrimaryKey.Equals(#1)",array[0], array[1]);
I have tried:data = data.where("GuidPrimaryKey.Contains(#0)",array); but that gives an error: No applicable method 'Contains' exists in type 'Guid'.
I also tried setting a loop to go through the elements in the array and set the where clause as a giant string, but that did not work either.
string s = "";
string p = ""
int counter = 0;
foreach(Guid g in Array)
{
s+= "GuidPrimaryKey.Equals(#" counter.ToString() + ") OR";
p += "Array[" counter.ToString() + "],";
counter++;
}
s = s.remove(s.length - 3, 3);
p = p.remove(p.length - 1, 1);
data = data.Where(s,p);
This gives me the error message: No Property or field '1' exists in type 'DynamicClass1'
Any ideas? I need to have the where clause build the query to check to see if the primary key (GuidPrimaryKey) exists in the list of keys (Guid[]).
I'm not sure if this works in the standard Dynamic Linq library, but I just tried this is my open-source version, and it works well:
var data = data.Where("GuidPrimaryKey in #0", array);
This also works:
var data = data.Where("#0.Contains(GuidPrimaryKey)", array);
Here is a full unit test I wrote to confirm this:
[TestMethod]
public void ExpressionTests_ContainsGuid()
{
//Arrange
//Generate some users with Id fields of type Guid
var userList = User.GenerateSampleModels(5, false);
var userQry = userList.AsQueryable();
//Generate a list of values that will fail.
var failValues = new List<Guid>() {
new Guid("{22222222-7651-4045-962A-3D44DEE71398}"),
new Guid("{33333333-8F80-4497-9125-C96DEE23037D}"),
new Guid("{44444444-E32D-4DE1-8F1C-A144C2B0424D}")
};
//Add a valid Guid so that this list will succeed.
var successValues = failValues.Concat(new[] { userList[0].Id }).ToArray();
//Act
var found1 = userQry.Where("Id in #0", successValues);
var found2 = userQry.Where("#0.Contains(Id)", successValues);
var notFound1 = userQry.Where("Id in #0", failValues);
var notFound2 = userQry.Where("#0.Contains(Id)", failValues);
//Assert
Assert.AreEqual(userList[0].Id, found1.Single().Id);
Assert.AreEqual(userList[0].Id, found2.Single().Id);
Assert.IsFalse(notFound1.Any());
Assert.IsFalse(notFound2.Any());
}

Concat not working - The underlying array is null

I am trying to Concat the two array IEnumerable lists and in result view it says The underlying array is null.
IEnumerable<ObjectToConcat> result = new ArraySegment<ObjectToConcat>();
var listA = new List<ObjectToConcat>();
var a = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "A Object"};
listA.Add(a);
var b = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "B Object"};
listA.Add(b);
// Error here is result view
result = result.Concat(listA);
var c = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "C Object"};
listB.Add(c);
// Error here is result view
result = result.Concat(listB);
Can anyone please suggest me what is wrong with my code. Or Concat does not work with List?
It would appear that this code:
IEnumerable<ObjectToConcat> result = new ArraySegment<ObjectToConcat>();
is an attempt to make an empty enumerable. You can do this more effectively and clearly by writing:
IEnumerable<ObjectToConcat> result = Enumerable.Empty<ObjectToConcat>();
That said, chaining a lot of Concat calls probably isn't the most effective, performance wise, if there are a lot of sub-lists. It's probably going to perform a bit better if you create a List<IEnumerable<ObjecToConcat>> allLists, add all of the sub-lists to that list, and then at the end you can write:
result = allLists.SelectMany(x => x);
to flatten it down to just a list of items.
you can have list of ObjectToConcat like below and add items to it using addrange method
List<ObjectToConcat> result = new List<ObjectToConcat>();
result.AddRange(listA);
Try this:
IEnumerable<ObjectToConcat> result =
new ArraySegment<ObjectToConcat>(new ObjectToConcat[0]).Array;

Categories